Exception handling allows developers to anticipate and manage these errors gracefully without crashing the application.
What is an Exception?
An exception is an event that disrupts the normal flow of a program. Common examples include:ZeroDivisionError: Division by zero
ValueError: Invalid value provided to a function
FileNotFoundError: Trying to open a file that doesn't exist
Example:
a = 10
b = 0
print(a / b) # ZeroDivisionError: division by zero
The try-except Block
Python provides the try-except block to handle exceptions gracefully without terminating the program.try:
num = int(input("Enter a number: "))
print(10 / num)
except ZeroDivisionError:
print("Error: Division by zero!")
except ValueError:
print("Error: Invalid input!")
The code inside the try block executes first. If an exception occurs, Python skips the remaining statements in the try block and transfers control to the matching except block.
If no exception occurs, all statements in the try block execute normally, and the except blocks are skipped.
If an exception occurs but none of the except blocks match its type, the exception propagates to the caller. If it is not handled anywhere in the program, Python terminates the program and displays a traceback.
A common way to handle any exception is to use a generic handler at the end:
try:
numbers = [10, 20]
print(numbers[5])
except ValueError:
print("Invalid value")
except ZeroDivisionError:
print("Cannot divide by zero")
except Exception as e:
print(f"Unexpected error: {e}")
Using else and finally
You can also use else and finally with try-except to handle logic more precisely.try:
num = int(input("Enter a number: "))
result = 10 / num
except ZeroDivisionError:
print("Cannot divide by zero.")
else:
print("Result:", result)
finally:
print("Execution completed.")
else → Runs only if no exception occurs.finally → Always executes, even if an error occurs — often used for cleanup (like closing files or releasing resources).
Raising Exceptions Manually
You can manually raise exceptions using the raise keyword.age = int(input("Enter your age: "))
if age < 18:
raise ValueError("You must be at least 18 years old.")
else:
print("Access granted.")
Creating Custom Exceptions
Sometimes, you need your own error types to represent application-specific issues. You can create a custom exception by extending the built-in Exception class.class AgeTooLowError(Exception):
"""Custom exception for invalid age"""
pass
def check_age(age):
if age < 18:
raise AgeTooLowError("Age must be at least 18.")
else:
print("Valid age.")
try:
check_age(15)
except AgeTooLowError as e:
print("Custom Exception:", e)
Handling Multiple Exceptions
You can handle multiple exceptions together:try:
x = int(input("Enter number: "))
print(10 / x)
except (ZeroDivisionError, ValueError) as e:
print("Error occurred:", e)
This keeps your code concise and efficient.
Summary
By using try, except, else, and finally, you can make your applications fault-tolerant and professional. Custom exceptions further enhance clarity and control, making your code more expressive and maintainable.| Concept | Description |
|---|---|
| try | Code block to test for errors |
| except | Handles exceptions that occur in try |
| else | Executes only if no exception occurs |
| finally | Executes regardless of whether an exception occurs |
| raise | Manually trigger an exception |
| Custom Exception | User-defined exception for specific errors |