嵌套导致python中的嵌套异常

Nested causes in nested exceptions in python

本问题已经有最佳答案,请猛点这里访问。

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

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

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

并在clientlib.py中

1
2
3
4
5
6
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中,什么是实现我想做的最佳实践?

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

1
2
3
4
5
6
7
8
9
10
11
12
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()

仅产生以下输出:

1
2
3
4
5
6
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发生的位置,所以在我的理解中,外部堆栈跟踪丢失了。


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

1
raise ClientException(...) from ioException

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

1
2
3
4
5
6
7
8
9
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