嵌套导致python中的嵌套异常

时间:2014-04-18 16:01:47

标签: python exception-handling

有没有办法在向链中传递内部异常时提供有关内部异常原因的信息(就像在具有Exception类的cause属性的java中一样)。

请考虑以下" python伪代码" (没有100%正确和发明的功能和类名)

try:
  clientlib.receive_data_chunk()
except ClientException as clientException:
  raise RuntimeError("reading from client failed" 
      + " (see nested exceptions for details)", cause=clientException)

并在clientlib.py

def receive_data_chunk():
  try:
    chunk = socket.read(20)
    return chunk
  except IOException as iOException:
    raise ClientException("couldn't read from client", cause = iOException)

如果不是在本地python中,那么实现我想做的最佳做法是什么?

请注意,我想保留内部和外部异常的堆栈跟踪,即以下解决方案不满意:

import sys

def function():
    try:
        raise ValueError("inner cause")
    except Exception:
        _, ex, traceback = sys.exc_info()
        message = "outer explanation (see nested exception for details)"
        raise RuntimeError, message, traceback

if __name__ == "__main__":
    function()

仅产生以下输出:

Traceback (most recent call last):
  File "a.py", line 13, in <module>
    function()
  File "a.py", line 6, in function
    raise ValueError("inner cause")
RuntimeError: outer explanation (see nested exception for details)

我无法看到RuntimeError发生的位置,所以在我的理解中,外部堆栈跟踪已丢失。

1 个答案:

答案 0 :(得分:5)

在Python 3中,您可以使用from关键字指定内部异常:

raise ClientException(...) from ioException

你得到一个如下所示的追溯:

Traceback (most recent call last):
  ...
IOException: timeout

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  ...
ClientException: couldn't read from client