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

后端 未结 15 2222
天命终不由人
天命终不由人 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:05

    A remark about this answer's comments: print(traceback.format_exc()) does a better job for me than traceback.print_exc(). With the latter, the hello is sometimes strangely "mixed" with the traceback text, like if both want to write to stdout or stderr at the same time, producing weird output (at least when building from inside a text editor and viewing the output in the "Build results" panel).

    Traceback (most recent call last):
    File "C:\Users\User\Desktop\test.py", line 7, in
    hell do_stuff()
    File "C:\Users\User\Desktop\test.py", line 4, in do_stuff
    1/0
    ZeroDivisionError: integer division or modulo by zero
    o
    [Finished in 0.1s]

    So I use:

    import traceback, sys
    
    def do_stuff():
        1/0
    
    try:
        do_stuff()
    except Exception:
        print(traceback.format_exc())
        print('hello')
    

提交回复
热议问题