You have saved the exception in a variable, err
. It's still bound to the exception, even after the except
block.
(The fact that print
on an exception doesn't show all that much is a separate issue.)
However, it sounds like you wanted the traceback object, not just the exception object. That doesn't get automatically bound to a variable for you, but you can do it manually:
try:
1/0
except Exception:
exc_type, exc_value, exc_traceback = sys.exc_info()
See exc_info
for more information.
But a traceback
object is a pretty heavy thing, and keeps all kinds of other heavy things alive as long as you store it. One way to avoid carrying around an object as heavy and inter-linked as the traceback is to extract just the information you want from it. That's what the traceback
module is for:
try:
1/0
except Exception:
exc_type, exc_value, exc_traceback = sys.exc_info()
exc_traceback = traceback.extract_tb(exc_traceback)
Now we're only carrying around a list of small tuples of strings and numbers, instead of the traceback object.
Or, even more simply, just format it immediately:
exc_traceback = traceback.format_tb(exc_traceback)