In this step, you will learn how to check for specific exception classes directly in your except
blocks. This is a more direct and often clearer way to handle exceptions compared to using isinstance()
.
Let's create a Python script to demonstrate this.
-
Open your VS Code editor.
-
Create a new file named exception_classes.py
in the ~/project
directory.
~/project/exception_classes.py
-
Add the following code to the exception_classes.py
file:
try:
result = 10 / 0
except ZeroDivisionError as e:
print("Caught a ZeroDivisionError:", e)
except ArithmeticError as e:
print("Caught an ArithmeticError:", e)
except Exception as e:
print("Caught some other exception:", e)
print("Program continues...")
In this script, we are trying to divide 10 by 0, which will raise a ZeroDivisionError
. We have three except
blocks: one for ZeroDivisionError
, one for ArithmeticError
, and one for Exception
.
-
Run the script using the following command in the terminal:
python exception_classes.py
This will print "Caught a ZeroDivisionError: division by zero" to the terminal.
Example output:
Caught a ZeroDivisionError: division by zero
Program continues...
The output shows that the ZeroDivisionError
was caught by the first except
block.
Now, let's modify the script to raise a different exception.
-
Modify the exception_classes.py
file to the following:
try:
result = int("abc")
except ZeroDivisionError as e:
print("Caught a ZeroDivisionError:", e)
except ValueError as e:
print("Caught a ValueError:", e)
except ArithmeticError as e:
print("Caught an ArithmeticError:", e)
except Exception as e:
print("Caught some other exception:", e)
print("Program continues...")
In this modified script, we are trying to convert the string "abc" to an integer, which will raise a ValueError
.
-
Run the script again using the same command:
python exception_classes.py
This will print "Caught a ValueError: invalid literal for int() with base 10: 'abc'" to the terminal.
Example output:
Caught a ValueError: invalid literal for int() with base 10: 'abc'
Program continues...
This output shows that the ValueError
was caught by the second except
block.
By specifying the exception class directly in the except
block, you can handle different types of exceptions in a clear and organized manner. This approach is generally preferred over using isinstance()
for simple exception handling.