how to catch all uncaught exceptions and go on?

后端 未结 2 1767
暗喜
暗喜 2021-01-20 10:15

EDIT: after reading the comments and the answers I realize that what I want to do does not make much sense. What I had in mind was that I h

相关标签:
2条回答
  • 2021-01-20 10:58

    Are you after:

    import traceback
    import sys
    
    try:
        raise ValueError("something bad happened, but we got that covered")
    except Exception:
        print("--------------")
        print(traceback.format_exception(sys.exc_info()))
        print("--------------")
    print("still there")
    
    0 讨论(0)
  • You can't do this because Python calls sys.excepthook for uncaught exceptions.

    In an interactive session this happens just before control is returned to the prompt; in a Python program this happens just before the program exits.

    There's no way to resume the execution of the program or "supress" the exception in sys.excepthook.

    The closest I can think of is

    try:
        raise ValueError("something bad happened, but we got that covered")
    finally:
        print("still there")
    

    There's no except clause, therefore ValueError won't be caught, but the finally block is guaranteed to be executed. Thus, the exception hook will still be called and 'still there' will be printed, but the finally clause will be executed before sys.excepthook:

    If an exception occurs in any of the clauses and is not handled, the exception is temporarily saved. The finally clause is executed. If there is a saved exception it is re-raised at the end of the finally clause.

    (from here)

    0 讨论(0)
提交回复
热议问题