Python's exception handling mechanism is a cornerstone of writing robust and error-resistant code. In this tutorial, we explore the try, except, else, and finally blocks, which allow developers to gracefully manage runtime errors.
The Basics of Exception Handling
When a program encounters an error, Python raises an exception. Without proper handling, the program crashes. The try block lets you test a block of code for errors, while the except block lets you handle the error.
Example:
try:
x = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
Using else
The else block runs if no exceptions occur in the try block. This is useful for code that should execute only when the try block succeeds.
try:
x = 10 / 2
except ZeroDivisionError:
print("Division error")
else:
print("Division successful, result:", x)
The finally Block
The finally block executes no matter what — whether an exception occurs or not. It's typically used for cleanup actions, like closing files or releasing resources.
try:
file = open("data.txt", "r")
# process file
except FileNotFoundError:
print("File not found")
finally:
file.close()
Best Practices
- Catch specific exceptions rather than using a bare
except. - Avoid using
except:without specifying an exception type. - Use
elseto separate success logic from error handling. - Always use
finallyfor cleanup tasks.
This lesson is part of a comprehensive Python course designed for 2026. By mastering these concepts, you'll be able to write resilient programs that handle unexpected situations smoothly.