我是靠谱客的博主 干净朋友,这篇文章主要介绍python捕获不到异常,在Python中记录未捕获的异常,现在分享给大家,希望可以做个参考。

How do you cause uncaught exceptions to output via the logging module rather than to stderr?

I realize the best way to do this would be:

try:

raise Exception, 'Throwing a boring exception'

except Exception, e:

logging.exception(e)

But my situation is such that it would be really nice if logging.exception(...) were invoked automatically whenever an exception isn't caught.

解决方案

As Ned pointed out, sys.excepthook is invoked every time an exception is raised and uncaught. The practical implication of this is that in your code you can override the default behavior of sys.excepthook to do whatever you want (including using logging.exception).

As a straw man example:

>>> import sys

>>> def foo(exctype, value, tb):

... print 'My Error Information'

... print 'Type:', exctype

... print 'Value:', value

... print 'Traceback:', tb

...

Override sys.excepthook:

>>> sys.excepthook = foo

Commit obvious syntax error (leave out the colon) and get back custom error information:

>>> def bar(a, b)

My Error Information

Type:

Value: invalid syntax (, line 1)

Traceback: None

最后

以上就是干净朋友最近收集整理的关于python捕获不到异常,在Python中记录未捕获的异常的全部内容,更多相关python捕获不到异常,在Python中记录未捕获内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(86)

评论列表共有 0 条评论

立即
投稿
返回
顶部