python - sys.exc_info() 是如何工作的?

标签 python exception python-2.7

sys.exc_info() 的行为在 python docs 中有描述。和 SOSO作为:

  • 在 except block 或由 except block 调用的方法中,描述异常的三元组
  • 在其他地方,三元组 None 值

那么为什么这个 nosetest 会失败呢?

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 block ,它将在那里失败。

我确实看到,如果我将所有这些放在一个方法中并从另一个方法调用,那么调用方法就不会看到异常。 exc_info 值似乎仍设置为抛出异常的方法的末尾,即使在处理异常之后也是如此。

我在 OSX 上使用 python2.7。

最佳答案

在回答你的问题之前,我必须解释一下 sys.exc_info() 决定了你程序中最新/最近的异常:-

Your program is basically a series of function calls, with caller function calling called. Thus a call stack/execution stack is formed, where an entry is pushed for each function, being called. This entry is known as stack frame in python. Thus, when in your program, sys.exc_info() is invoked, it uses the following sequence to determining latest exception. It begins from the current stack frame, which is the function from where you are invoking sys.exc_info(). If the current stack frame is not handling/had not handled an exception, the information is taken from the calling stack frame, or its caller, and so on until a stack frame is found that is handling/had handled an exception . Here, “handling an exception” is defined as “executing or having executed an except clause.” For any stack frame, only information about the most recently handled exception is accessible.

现在,开始你的代码,

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?

按照上面解释的过程,sys.exc_info() 总是会发现最近在您的函数中处理的异常。因此,除非您显式调用 sys.exec_clear(),否则它永远不会是 Nones 的元组。

希望对你有帮助。

关于python - sys.exc_info() 是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16974489/

相关文章:

python - 当引用计数为零时,文件对象会自动关闭吗?

java - Java中抛出异常的顺序

c++ - 在 C++ 析构函数中发生异常时,是否所有属性都自动销毁

javascript - 如何在python中将网页表数据转换为json对象或dict

python - 从 Bat 文件调用 Python 并获取返回码

python - 如何在 macos 上使用 opencv 和 python

java - 实现方法抛出异常,但接口(interface)方法未定义,因为它抛出异常

python-2.7 - Kinesis Agent 报告 python 流数据错误

python - 如何将 protobuf 图形转换为二进制线格式?

python - sqlalchemy 没有设置时间戳默认值