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

1 投票
1 回答
930 浏览
提问于 2025-04-18 03:17

有没有办法在传递内部异常时提供一些关于它发生原因的信息?就像在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 个回答

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

撰写回答