Python: 捕获未捕获的异常但不立即退出

Python: catch uncaught Exception but not exit immediately

来自 sys 模块的标准库

sys.excepthook(type, value, traceback)

This function prints out a given traceback and exception to sys.stderr.

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.

是否有任何方法可以捕获未捕获的异常 必须立即退出(取决于决策过程)?

以后
我想答案是否定的。我想 BDFL 以他的智慧提供了这个最后的机会,可以在它崩溃之前从一个崩溃的、不好的程序中抢救一些面包屑,只留下一些日志。

Below except: 可以捕获所有未捕获的异常,但这可能会产生意想不到的后果。更好的方法是编写单元测试并主动为可能的异常做准备,例如孩子在表单中抛出 unicode。

try:
  # do something

except Exception_Type:
  # do something else

except:
  # woops didn't count on that