如何捕获所有未捕获的异常并继续?

how to catch all uncaught exceptions and go on?

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 have some places in my code which may fail (usually some requests calls which may not go though) and I wanted to catch them instead of putting a try: everywhere. My specific problem was such that I would not care if they fail and would not influence the rest of the code (say, a watchdog call).

I will leave this question for posterity as an ode to "think about the real problem first, then ask"

我正在尝试处理所有未捕获(否则未处理)的异常:

import traceback
import sys

def handle_exception(*exc_info):
    print("--------------")
    print(traceback.format_exception(*exc_info))
    print("--------------")

sys.excepthook = handle_exception
raise ValueError("something bad happened, but we got that covered")
print("still there")

这输出

--------------
['Traceback (most recent call last):\n', '  File "C:/Users/yop/.PyCharm50/config/scratches/scratch_40", line 10, in <module>\n    raise ValueError("something bad happened, but we got that covered")\n', 'ValueError: something bad happened, but we got that covered\n']
--------------

所以,虽然加注确实被抓住了,但它并没有像我想的那样工作:调用 handle_exception,然后用 print("still there").

恢复

我该怎么做?

你在追求:

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")

你不能这样做,因为 Python 调用 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.

无法恢复程序的执行或 "supress" sys.excepthook 中的异常。

我能想到的最接近的是

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

没有except子句,所以ValueError不会被捕获,但是finally块肯定会被执行。因此,异常挂钩仍将被调用并打印 'still there',但是 finally 子句将在 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.

(来自 here