Handle specific error #
Using except the way we did in the previous lesson would catch all error types that occurred inside the try block, which is generally considered a bad practice. Instead of using a broad except statement, it is generally recommended to catch and handle specific exceptions that you expect may occur in your code.
The error type is usually at the bottom of the error message. For example, in the output below, we can see that the error type when we divide by zero is ZeroDivisionError.
Traceback (most recent call last):
File "main.py", line 1, in <module>
10 / 0
ZeroDivisionError: division by zero # <-- The error type
We can catch a specific type of error with except by using the following syntax:
try:
# code to run
except error_type:
# code to run of the error occurs.
For example, we can catch ZeroDivisionError the same way we did in our previous lesson with the code below:
try:
10 / 0
except ZeroDivisionError: <-- Specify the error type to catch
print("Error: Cannot divide the number by zero")
print("The program is running")
# Output
Error: Cannot divide the number by zero
The program is running
If the error occurred due to another reason, such as dividing a number with a string, the program will stop running and raises another error. In that case, the error raised is the TypeError instead of ZeroDivisionError:
try:
10 / "OKAY"
except ZeroDivisionError:
print("Error: Cannot divide the number by zero")
print("The program is running")
# Output
Traceback (most recent call last):
File "main.py", line 2, in <module>
10 / "OKAY"
TypeError: unsupported operand type(s) for /: 'int' and 'str'
Exercise #
- Update the
divide_the_numberfunction to handle onlyZeroDivisionError.
Tests #
divide_the_number(4, 2)should return2.0divide_the_number(10, 4)should return2.5divide_the_number(10, 0)should print the message"You cannot divide by zero!"divide_the_number(10, "Hello")should cause an errorTypeErrorand not print the message"You cannot divide by zero!"
Getting Started with Python
Data Types
Python Functions
Statements in Python
Basic Debugging in Python
Basic Algorithm
Object-Oriented Programming
Error Handling
Intermediate Algorithm
Python Modules