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 atry:
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?
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)