🧩 Python Exception Handling
In Python, exceptions are errors that occur during program execution.
Instead of crashing the entire program, Python allows you to handle these errors gracefully using Exception Handling.
For example, dividing a number by zero or accessing an invalid index will raise an exception.
Example (without handling):
a = 10 b = 0 print(a / b) # Error: ZeroDivisionError
➡️ Output:
ZeroDivisionError: division by zero
To prevent the program from crashing, we use try-except blocks.
To avoid program crashes due to runtime errors
To provide user-friendly messages instead of technical errors
To ensure program continues even after errors
To debug and log errors effectively
The try block contains the code that might cause an error,
and the except block handles the error when it occurs.
Syntax:
try: # code that may raise an error except: # code to handle the error
Example:
try: a = int(input("Enter a number: ")) print(10 / a) except: print("Something went wrong!")
You can handle specific types of exceptions like ZeroDivisionError, ValueError, TypeError, etc.
Example:
try: a = int(input("Enter a number: ")) print(10 / a) except ZeroDivisionError: print("Cannot divide by zero!") except ValueError: print("Please enter a valid number!")
The else block executes only if no error occurs in the try block.
Example:
try: num = int(input("Enter a number: ")) print("Square =", num ** 2) except ValueError: print("Invalid input! Please enter a number.") else: print("Execution successful!")
The finally block always executes — whether an error occurs or not.
It’s often used for cleanup actions (like closing files or releasing resources).
Example:
try: f = open("data.txt", "r") print(f.read()) except FileNotFoundError: print("File not found!") finally: print("Program ended.")
You can manually raise an exception using the raise keyword.
Syntax:
raise ExceptionType("Custom error message")
Example:
age = int(input("Enter your age: ")) if age < 18: raise ValueError("You must be 18 or older!") else: print("Access granted.")
You can also use a try-except block inside another try block.
Example:
try: a = int(input("Enter number: ")) try: result = 10 / a print("Result:", result) except ZeroDivisionError: print("Division by zero not allowed.") except ValueError: print("Invalid input.")
| Exception Type | Description |
|---|---|
| ZeroDivisionError | Division by zero |
| ValueError | Invalid value given to a function |
| TypeError | Operation on incompatible data types |
| IndexError | Accessing invalid list/tuple index |
| KeyError | Accessing non-existent key in a dictionary |
| FileNotFoundError | File not found on disk |
| NameError | Using an undefined variable |
| AttributeError | Invalid attribute access |
| ImportError | Module import failed |
✅ Example 1: Safe Division
def safe_divide(a, b): try: result = a / b print("Result:", result) except ZeroDivisionError: print("Error: Cannot divide by zero!") except TypeError: print("Error: Invalid data type!") safe_divide(10, 2) safe_divide(5, 0) safe_divide("a", 3)
✅ Example 2: File Handling with Exception
try: file = open("sample.txt", "r") print(file.read()) except FileNotFoundError: print("File not found! Please check the filename.") finally: print("File operation complete.")
✅ Example 3: Custom Exception
class InvalidAgeError(Exception): pass age = int(input("Enter your age: ")) try: if age < 18: raise InvalidAgeError("You are not eligible!") else: print("Eligible for registration.") except InvalidAgeError as e: print(e)
Division Program:
Input two numbers and handle ZeroDivisionError and ValueError.
File Reader:
Try to open a file — handle FileNotFoundError.
Custom Exception:
Create a custom exception if a user enters a negative number.
Nested Try Block:
Handle invalid input and division error in nested try-except.
Use finally:
Write a program that always prints “Program ended” even if an error occurs.