Asked By – codersofthedark
I want to save the name of the error and the traceback details into a variable. Here’s is my attempt.
import sys try: try: print x except Exception, ex: raise NameError except Exception, er: print "0", sys.exc_info() print "1", sys.exc_info() print "2", sys.exc_info()
0 <type 'exceptions.NameError'> 1 2 <traceback object at 0xbd5fc8>
0 NameError 1 2 Traceback (most recent call last): File "exception.py", line 6, in <module> raise NameError
P.S. I know this can be done easily using the traceback module, but I want to know usage of sys.exc_info() object here.
Now we will see solution for issue: How to save traceback / sys.exc_info() values in a variable?
This is how I do it:
>>> import traceback >>> try: ... int('k') ... except: ... var = traceback.format_exc() ... >>> print var Traceback (most recent call last): File "<stdin>", line 2, in <module> ValueError: invalid literal for int() with base 10: 'k'
You should however take a look at the traceback documentation, as you might find there more suitable methods, depending to how you want to process your variable afterwards…