sys.exc_info()如何工作? [英] How sys.exc_info() works?

查看:237
本文介绍了sys.exc_info()如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

python docs 中描述了sys.exc_info()的行为以及 SO SO 作为:

The behavior of sys.exc_info() is described in python docs and on SO and SO as:


  • 在一个不同的块或由一个除外块调用的方法中,一个三元组描述异常

  • 其他地方,三个无值

那么为什么这个nosetest失败?

So why does this nosetest fail?

def test_lang_stack(self):
    try:
        self.assertEquals((None,None,None), sys.exc_info()) # no exception
        a = 5 / 0
    except:
        self.assertNotEquals((None,None,None), sys.exc_info())  # got exception
    else:
        self.fail('should not get here')
    #finally:
    #    self.assertEquals((None,None,None), sys.exc_info()) # already handled, right?
    self.assertEquals((None,None,None), sys.exc_info())  # already handled, right?

在最后一行失败。如果你取消注释finally块,那么它就会失败。

It fails at the last line. If you uncomment the finally block, it fails there instead.

我确实看到,如果我将所有内容放在一个方法中,并从另一种方法调用,那么调用方法没有看到异常。即使在处理异常之后,exc_info值似乎仍然保留在抛出异常的方法的末尾。

I do see that if I put all this inside one method and call from a different method, then the calling method does not see the exception. The exc_info value seems to remain set to the end of the method where an exception is thrown, even after the exception is handled.

我在OSX上使用python2.7

I'm using python2.7 on OSX.

推荐答案

在assertEquals()和assertNotEquals()中,您需要调用:

In both assertEquals() and assertNotEquals() you need to call:

sys.exc_clear()

清除下一个错误的东西。

This will clear things for the next error.

这篇关于sys.exc_info()如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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