【发布时间】: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 相关问题中广泛使用。