【问题标题】:Nested causes in nested exceptions in python [duplicate]python中嵌套异常中的嵌套原因[重复]
【发布时间】:2014-06-03 04:16:54
【问题描述】:

有没有办法在将内部异常传递到链上时提供有关内部异常原因的信息(就像在 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)

在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 发生在哪里,所以据我了解,外部堆栈跟踪丢失了。

【问题讨论】:

  • 查看这个 (stackoverflow.com/questions/1350671/…) 问题,它会询问并回答您想知道的内容(只是用不同的术语。)
  • 我同意。我想编辑引用问题的标题以包含术语 cause 以改进搜索是有意义的,因为它在 Java 相关问题中广泛使用。

标签: python exception-handling


【解决方案1】:

在 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

【讨论】:

  • 太好了,这正是我要找的!
猜你喜欢
  • 2017-02-13
  • 2015-04-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-25
  • 2015-06-06
  • 2013-05-26
相关资源
最近更新 更多