sys.excepthook -vs- handled exceptions

夙愿已清 提交于 2020-01-05 04:27:14

问题


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

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