how to catch all uncaught exceptions and go on?

爷,独闯天下 提交于 2019-12-02 04:53:51

问题


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"

I am trying to handle all uncaught (otherwise unhandled) exceptions:

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

This outputs

--------------
['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']
--------------

So, while the raise was indeed caught, it did not work the way I thought: a call to handle_exception, then resume with the print("still there").

How can I do so?


回答1:


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)




回答2:


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


来源:https://stackoverflow.com/questions/33985027/how-to-catch-all-uncaught-exceptions-and-go-on

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!