Catch any error in Python

前端 未结 8 1668
一个人的身影
一个人的身影 2021-02-01 14:24

Is it possible to catch any error in Python? I don\'t care what the specific exceptions will be, because all of them will have the same fallback.

8条回答
  •  梦毁少年i
    2021-02-01 15:08

    You might want also to look at sys.excepthook:

    When an exception is raised and uncaught, the interpreter calls sys.excepthook with three arguments, the exception class, exception instance, and a traceback object. 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. The handling of such top-level exceptions can be customized by assigning another three-argument function to sys.excepthook.

    Example:

    def except_hook(type, value, tback):
        # manage unhandled exception here
        sys.__excepthook__(type, value, tback) # then call the default handler
    
    sys.excepthook = except_hook
    

提交回复
热议问题