Accessing the error object #
When handling exceptions using try-except blocks in Python, it's often useful to access and work with the error object itself. The error object provides valuable information about the exception that occurred, allowing you to customize error handling, log the error, or extract specific details.
We can access the error object by using the keyword as after the error types in the except clause, like so:
try:
10 / 0
except (TypeError, ZeroDivisionError) as e:
print(type(e)) # <class 'ZeroDivisionError'>
print(e) # division by zero
if type(e) == ZeroDivisionError:
print("This error is caused by zero division")
else:
print("This error is caused by something else")
In the example above, we get the error object and assign it to the variable e with the code as e. We can choose any other name that we prefer. We can call the function type() to check the type of the error, which we can see that it is simply a class named ZeroDivisionError. We could even use if else statement to handle the error as well.
Exercise #
- Update the function
divide_the_numerto handle multiple types of error.
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 print the message"You cannot divide a number with a string!"- Must use only one
exceptin the function
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