How to catch and print the full exception traceback without halting/exiting the program?

chriscauley picture chriscauley · Sep 13, 2010 · Viewed 758.8k times · Source

I want to catch and log exceptions without exiting, e.g.,

try:
    do_stuff()
except Exception, err:
    print(Exception, err)
    # I want to print the entire traceback here,
    # not just the exception name and details

I want to print the exact same output that is printed when the exception is raised without the try..except intercepting the exception, and I do not want it to exit my program. How do I do this?

Answer

volting picture volting · Sep 13, 2010

traceback.format_exc() or sys.exc_info() will yield more info if that's what you want.

import traceback
import sys

try:
    do_stuff()
except Exception:
    print(traceback.format_exc())
    # or
    print(sys.exc_info()[2])