except as
- Python course
- Intermediate
- Lesson 85/116
- 5 min
Learn the exception object with except E as e.
Accessing the object with except ... as
To bind the caught error to a variable you write except ValueError as e:. The e variable holds the error object; you can get the message with str(e) and the type name with type(e).__name__.
This access is needed to show a meaningful message to the user. For example print("Error:", e) prints what the error was. The error object also has properties like .args; this gives the error's parameters as a tuple.
Practice Bind the error to e and print
In a try block call value = int("abc"). In except ValueError as e: write print("Error:", e). The error message is printed.
Starter code
# Try a number conversion in a try block
# Bind the error to e and print itSample solution
# Call int("abc") in a try block
try:
value = int("abc")
# In except ValueError as e: print the error
except ValueError as e:
print("Error:", e)Expected output
Error: invalid literal for int() with base 10: 'abc'
Attributes on e
The error object's e.args attribute gives the error's parameters as a tuple. str(e) joins these into a readable message. type(e).__name__ gives the error class's name.
These attributes are useful when logging errors. For instance with type(e).__name__ you record the error type, with str(e) the message, and with e.args the parameters. This speeds up debugging.
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 In except ValueError as e, what is e?
- The error type name
- The error object itself Correct answer
- The line number that raised
- The error message string
Explanation: e is a ValueError instance; str(e) gives its message.
2 Match the error object attributes
| Term | Meaning |
|---|---|
as e |
Binds the object to e |
str(e) |
Error message |
type(e).__name__ |
Type name |
e.args |
Parameter tuple |
3 Complete the as e clause
except ValueError ____ e:
print(e)
except ValueError as e:
print(e)
Explanation: as e binds the error object to e.