python中嵌套异常中的嵌套原因

Kar*_*ter 1 python exception-handling

有没有一种方法可以在向上传递内部异常时提供有关内部异常原因的信息(就像在Java中使用Exception类的cause属性那样)。

请考虑以下“ python伪代码”(没有100%正确和虚​​构的函数和类名)

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

并在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)
Run Code Online (Sandbox Code Playgroud)

如果不在本地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()
Run Code Online (Sandbox Code Playgroud)

仅产生以下输出:

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)
Run Code Online (Sandbox Code Playgroud)

我看不到RuntimeError发生的位置,所以据我了解,外部堆栈跟踪丢失了。

nne*_*neo 5

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

raise ClientException(...) from ioException
Run Code Online (Sandbox Code Playgroud)

您将得到如下所示的回溯:

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
Run Code Online (Sandbox Code Playgroud)