sys.excepthook -vs-处理的异常 [英] sys.excepthook -vs- handled exceptions

查看:100
本文介绍了sys.excepthook -vs-处理的异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我注意到处理的异常不会导致对sys.excepthook ...的调用,这回想起来很有意义.

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

我希望能够记录处理ZeroDivisionError的事实.

I would like to be able to log the fact that a ZeroDivisionError was handled.

有没有办法做到这一点?

Is there a way to do this?

推荐答案

您可以获取Exception并打印有关它的信息,或者使用您自己的记录调用对其进行记录:

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

结果:

a ZeroDivisionError was not raised

如果您正在寻找某种全局异常处理,那可能不容易,或者不可能,而不会将所有内容都包含在try/except中.

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.

这篇关于sys.excepthook -vs-处理的异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆