Errors are a part of every programmer's life. Instead of letting your Python program crash when something goes wrong, you can use error handling to manage exceptions gracefully. Python provides powerful tools like try
, except
, else
, and finally
to handle errors in a clean and effective way.
In this post, you'll learn how to catch and handle exceptions in Python using practical examples that demonstrate the best practices of writing robust code.
1. What is an Exception?
An exception is an event that interrupts the normal flow of a program. Common examples include:
ZeroDivisionError
– Dividing by zeroFileNotFoundError
– Trying to open a non-existent fileTypeError
– Performing an invalid operation on a data typeValueError
– Passing an inappropriate value to a function
2. Basic Try-Except Block
try:
x = 10 / 0
except ZeroDivisionError:
print("You can't divide by zero.")
This prevents the program from crashing and gives a friendly error message.
3. Catching Multiple Exceptions
try:
number = int("abc")
except ValueError:
print("Cannot convert to integer.")
except TypeError:
print("Invalid type.")
4. Using a General Exception Handler
try:
result = 5 / 0
except Exception as e:
print("An error occurred:", e)
This approach is useful for debugging or catching unexpected errors, but should be used cautiously.
5. The else
Block
else
runs if no exceptions are raised.
try:
x = 100 / 2
except ZeroDivisionError:
print("Division error.")
else:
print("Result is:", x)
6. The finally
Block
finally
is always executed, whether an exception is raised or not. It's useful for cleanup actions.
try:
file = open("data.txt", "r")
print(file.read())
except FileNotFoundError:
print("File not found.")
finally:
print("End of file operation.")
7. Raising Your Own Exceptions
You can raise exceptions using the raise
keyword.
age = -5
if age < 0:
raise ValueError("Age cannot be negative.")
8. Handling File Errors
try:
with open("nonexistent.txt", "r") as file:
print(file.read())
except FileNotFoundError:
print("The file you're trying to open does not exist.")
9. Custom Exception Class (Advanced)
class CustomError(Exception):
pass
try:
raise CustomError("Something custom went wrong.")
except CustomError as ce:
print(ce)
10. Summary Table
Keyword | Description |
---|---|
try |
Block to test code for errors |
except |
Block that handles the error |
else |
Runs if no error occurs |
finally |
Runs no matter what |
raise |
Manually trigger an exception |
11. Final Thoughts
Error handling is a vital part of writing resilient programs. By using try
, except
, else
, and finally
, you can anticipate and respond to runtime issues, ensuring that your code continues to run smoothly and users get proper feedback when something goes wrong.