问题
I noticed that exceptions that are handled do not result in a call to sys.excepthook
... which makes sense in retrospect.
But, how do I log or otherwise customize the way that handled exceptions are dealt with? When this code executes...
try:
1/0
except:
pass
I would like to be able to log the fact that a ZeroDivisionError
was handled.
Is there a way to do this?
回答1:
You can get the Exception
and print info about it or log that with a logging call of your own:
try:
1/0
except Exception, e:
print("a {0} was not raised".format(e.__class__.__name__))
# or logging.yourLogger(e.__class__.__name__)
pass
Result:
a ZeroDivisionError was not raised
If you were looking for some kind of Global Exception Handling, that is probably not trivial or not possible without enclosing everything in try/except
.
来源:https://stackoverflow.com/questions/49001647/sys-excepthook-vs-handled-exceptions