In Python, exceptions are errors that occur during program execution, which can disrupt the normal flow. Exception handling allows you to catch and manage these errors, preventing your program from crashing and providing meaningful feedback to users.
Python provides a flexible mechanism for handling runtime errors using try, except, else, finally, and raise statements.
Why Exception Handling Is Important
- Prevents program crashes during runtime
- Helps debug and log errors efficiently
- Allows graceful recovery from unexpected events
- Improves user experience by providing meaningful messages
Example:
try:
num = int(input("Enter a number: "))
print(10 / num)
except ZeroDivisionError:
print("Cannot divide by zero!")
except ValueError:
print("Please enter a valid integer.")
Python Exception Handling Structure
1. try Block
The code that may cause an error is placed inside a try block.
try:
x = 10 / 0
except ZeroDivisionError:
print("Division by zero error")
2. except Block
Catches and handles specific exceptions. You can also catch multiple exceptions.
try:
x = int("abc")
except (ValueError, TypeError) as e:
print("Error occurred:", e)
3. else Block
Executes if the try block does not raise any exception.
try:
x = 10 / 2
except ZeroDivisionError:
print("Error!")
else:
print("Division successful!")
4. finally Block
Always executes, whether an exception occurs or not. Often used for cleanup.
try:
file = open("example.txt", "r")
except FileNotFoundError:
print("File not found")
finally:
print("Execution complete")
5. raise Statement
Manually triggers an exception when a specific condition occurs.
age = -5
if age < 0:
raise ValueError("Age cannot be negative")
Common Python Exceptions
| Exception | Description |
|---|---|
| ZeroDivisionError | Division by zero |
| ValueError | Invalid data type or value |
| FileNotFoundError | File does not exist |
| IndexError | Index out of range |
| KeyError | Dictionary key not found |
| TypeError | Invalid operation on data types |
Best Practices for Exception Handling
✔ Catch only specific exceptions, not general Exception
✔ Use meaningful error messages
✔ Avoid using exception handling for normal logic
✔ Always clean up resources using finally
Conclusion
Exception handling is a critical skill in Python. By using try, except, else, finally, and raise, developers can write robust, error-proof programs that handle unexpected events gracefully, improve reliability, and enhance user experience.
References
- Internal Reference: https://savanka.com/category/learn/python/
- External Reference: https://www.w3schools.com/python/