Access Exception args
In this step, you will learn how to access the arguments (args) associated with an exception in Python. Exception arguments can provide more specific details about the error that occurred.
Let's modify the exceptions.py
file you created in the previous step to access and print the exception arguments. Open exceptions.py
in your ~/project
directory using the VS Code editor.
## exceptions.py
def divide(x, y):
try:
result = x / y
print("The result is:", result)
except Exception as e:
print("An error occurred:", type(e), e.args)
divide(10, 2)
divide(10, 0)
divide("hello", 5)
In this code, we've modified the except
block to print e.args
. The args
attribute is a tuple containing the arguments that were passed to the exception's constructor.
Now, run the exceptions.py
script:
python exceptions.py
You should see the following output:
The result is: 5.0
An error occurred: <class 'ZeroDivisionError'> ('division by zero',)
An error occurred: <class 'TypeError'> ("unsupported operand type(s) for /: 'str' and 'int'",)
As you can see, the output now includes the arguments associated with each exception. For ZeroDivisionError
, the argument is a tuple containing the string 'division by zero'
. For TypeError
, the argument is a tuple containing the string "unsupported operand type(s) for /: 'str' and 'int'"
.
Let's modify the exceptions.py
file again to access the first argument directly:
## exceptions.py
def divide(x, y):
try:
result = x / y
print("The result is:", result)
except Exception as e:
print("An error occurred:", type(e), e.args[0])
divide(10, 2)
divide(10, 0)
divide("hello", 5)
Run the script again:
python exceptions.py
You should see the following output:
The result is: 5.0
An error occurred: <class 'ZeroDivisionError'> division by zero
An error occurred: <class 'TypeError'> unsupported operand type(s) for /: 'str' and 'int'
By accessing e.args[0]
, we can extract the first argument of the exception, which is often the most descriptive part of the error message.