Python 3.x(beazley):异常处理中的__context__ vs __cause__属性

时间:2014-11-14 06:15:38

标签: python python-3.x

在'链式例外'中 - Beazley pg:626

try:
  pass
except ValueError as e:
  raise SyntaxError('foo bar') from e

这里,如果引发了ValueError并且随后引发了SyntaxError,则“e”包含__cause__,它指向ValueError Traceback。他接着说:

A more subtle example of exception chaining involves exceptions raised within
another exception handler. For example:
def error(msg):
  print(m)          # Note: typo is intentional (m undefined)
try:
  statements
except ValueError as e:
  error("Couldn't parse configuration")

在这里,'错误'会产生无意的异常。我不明白的是这一点:

For implicit chaining, the _ _context_ _ attribute of an exception instance 
e contains a reference to previous exception.

为什么他说'e'在__context__中包含对'error'生成的异常的引用?那是对的吗?当然,“错误”产生的异常将引用“e”?

1 个答案:

答案 0 :(得分:2)

您在问题中提出了一个问题,并在评论中提出了另一个问题。

问题中的问题:

我不认为“异常实例e”必然是指该代码示例中的异常e。它只是表示“处理早期异常时出现的任何异常实例”。因此,该语句仅表示如果正在处理一个异常(例如e1),并且在处理期间会引发另一个异常(e2),那么e2将传播,{{1 }}将设置为e2.__context__

关于你在评论中提出的问题,我认为你是误会。没有“隐式生成异常”。 两个异常之间的关系可以是隐式或显式的。通过使用e1,您明确了两者之间的关系(即,一个是“故意”从另一个创建的)。如果你不使用raise ... from ...,那么这种关系是隐含的(第二种关系只是在处理第一种情况时发生的)。

它的工作方式是,如果在处理一个异常时引发新的异常,那么新异常将在新异常的from属性中具有旧异常。但是,如果新异常包含__context__子句(from),则新异常将在其raise NewException from OldException属性中另外包含旧异常。

示例:

__cause__