In Python, errors that occur during program execution are called exceptions. While you can use a generic except
block to catch any exception, it's considered best practice to handle specific exceptions. Doing so allows your program to react precisely to different types of errors and improves readability and debugging.
In this guide, you’ll learn how to catch and handle specific exceptions like ZeroDivisionError
, ValueError
, FileNotFoundError
, and others using practical examples.
1. Why Handle Specific Exceptions?
- Prevents catching unexpected errors
- Improves program control and accuracy
- Makes debugging easier
- Enhances code readability
2. Handling ZeroDivisionError
try:
result = 10 / 0
except ZeroDivisionError:
print("Error: Cannot divide by zero.")
Output: Error: Cannot divide by zero.
3. Handling ValueError
This error occurs when a function receives the right type of argument but an inappropriate value.
try:
number = int("abc")
except ValueError:
print("Error: Please enter a valid integer.")
Output: Error: Please enter a valid integer.
4. Handling FileNotFoundError
This exception occurs when you try to open a file that doesn't exist.
try:
with open("missing_file.txt", "r") as file:
content = file.read()
except FileNotFoundError:
print("Error: File not found.")
5. Handling TypeError
This happens when an operation is performed on incompatible data types.
try:
result = "5" + 2
except TypeError:
print("Error: You can't add a string and an integer.")
6. Handling IndexError
Occurs when trying to access an index that’s out of range in a list.
try:
fruits = ["apple", "banana"]
print(fruits[5])
except IndexError:
print("Error: Index out of range.")
7. Handling KeyError
This error occurs when a dictionary key is not found.
try:
person = {"name": "Alice"}
print(person["age"])
except KeyError:
print("Error: Key does not exist in the dictionary.")
8. Handling Multiple Specific Exceptions
try:
value = int("xyz")
result = 10 / 0
except ValueError:
print("Caught a value error.")
except ZeroDivisionError:
print("Caught a division error.")
9. Using a Tuple for Multiple Exceptions
try:
risky_code = int("hello") + 10 / 0
except (ValueError, ZeroDivisionError) as e:
print("Handled multiple exceptions:", e)
10. Summary Table
Exception Type | Cause | Example |
---|---|---|
ZeroDivisionError |
Division by zero | 10 / 0 |
ValueError |
Invalid value for an operation | int("abc") |
FileNotFoundError |
Opening a non-existent file | open("missing.txt") |
TypeError |
Invalid type usage | "5" + 2 |
IndexError |
Accessing an out-of-range index | list[10] |
KeyError |
Missing key in dictionary | dict["missing"] |
11. Final Thoughts
Handling specific exceptions allows your program to respond intelligently to different error situations. It also helps prevent bugs from being masked and ensures that users receive clear feedback. Always prefer handling known exceptions directly and reserve generic except Exception
blocks for truly unknown cases.