When debugging Python code at the interactive prompt (REPL), often I\'ll write some code which raises an exception, but I haven\'t wrapped it in a try
/exc
The sys
module provides some functions for post-hoc examining of exceptions: sys.last_type, sys.last_value, and sys.last_traceback.
sys.last_value
is the one you're looking for.
As @Cairnarvon mentioned, I didn't find any last_value
member is sys module.
sys.exc_info()
did the trick for me. sys.exc_info()
returns a tuple with three values (type, value, traceback)
.
So sys.exc_info()[1]
will give the readable error. Here is the example,
import sys
list = [1,2,3,4]
try:
del list[8]
except Exception:
print(sys.exc_info()[1])
will output list assignment index out of range
Also, traceback.format_exc()
from traceback
module can be used to print out the similar information.
Below is the output if format_exec()
is used,
Traceback (most recent call last):
File "python", line 6, in <module>
IndexError: list assignment index out of range