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

后端 未结 15 2250
天命终不由人
天命终不由人 2020-11-22 13:46

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 entir         


        
15条回答
  •  野性不改
    2020-11-22 14:07

    To get the precise stack trace, as a string, that would have been raised if no try/except were there to step over it, simply place this in the except block that catches the offending exception.

    desired_trace = traceback.format_exc(sys.exc_info())
    

    Here's how to use it (assuming flaky_func is defined, and log calls your favorite logging system):

    import traceback
    import sys
    
    try:
        flaky_func()
    except KeyboardInterrupt:
        raise
    except Exception:
        desired_trace = traceback.format_exc(sys.exc_info())
        log(desired_trace)
    

    It's a good idea to catch and re-raise KeyboardInterrupts, so that you can still kill the program using Ctrl-C. Logging is outside the scope of the question, but a good option is logging. Documentation for the sys and traceback modules.

提交回复
热议问题