Five Steps to Access and Format Exception Objects in Python
1 min readApr 15, 2021
The aim of this pagešis to outline 5 steps for accessing exception objects and formatting their content. From the great Core Python course on Pluralsight.
1. five steps
import sys
at the top of your script- use
as
clause at the end of theexcept
statement and create an alias for the error object (e.g.e
) - print error message with an
f string
- use
f"{e!r}"
inserting the repl representation into your strings. In case of exception objects, this gives us more info about the type of the exception - pass a keyword argument
file=sys.stderr
into theprint
statement
2. example
import sys #1
DIGIT_MAP = {
'zero': '0',
'one': '1',
'two': '2',
'three': '3',
'four': '4',
'five': '5',
'six': '6',
'seven': '7',
'eight': '8',
'nine': '9',
}def convert(s):
number = ''
x = -1
try:
for token in s:
number += DIGIT_MAP[token]
x = int(number)
print(f"Conversion Succeded. x = {x}")
except (KeyError, TypeError) as e: #2
print(f"{e!r}", file=sys.stderr) #3-5
return xprint(convert(512)
- this returns
TypeError("'int' object is not iterable")
-1