Inspect the Exception Type
In this step, you will learn how to inspect the exception type and access the exception message within the except
block. This allows you to handle different types of exceptions in different ways and provide more informative error messages.
When an exception is caught, you can assign it to a variable in the except
clause using the as
keyword:
try:
## Code that might raise an exception
except ExceptionType as e:
## Code to handle the exception
## 'e' is the exception object
The variable e
will then contain the exception object, which you can use to access information about the exception, such as its type and message.
Let's modify the division.py
file to inspect the exception type and print the exception message:
-
Open the division.py
file in the VS Code editor.
-
Modify the code to inspect the exception type and print the message:
try:
numerator = 10
denominator = 0
result = numerator / denominator
print(result)
except ZeroDivisionError as e:
print(f"Error: {type(e).__name__} - {e}")
In this code, we catch the ZeroDivisionError
and assign it to the variable e
. We then use type(e).__name__
to get the name of the exception type and e
to get the exception message. We print both in a formatted string.
-
Run the script using the following command in the terminal:
python division.py
You will see the following output:
Error: ZeroDivisionError - division by zero
The output now includes the exception type (ZeroDivisionError
) and the exception message (division by zero
).
This allows you to provide more detailed information about the error that occurred, making it easier to debug your code. You can also use this information to handle different types of exceptions in different ways, providing more specific error handling for each case.