【发布时间】:2010-11-23 22:53:50
【问题描述】:
我的背景是 C#,我最近才开始使用 Python 进行编程。当抛出异常时,我通常希望将其包装在另一个添加更多信息的异常中,同时仍显示完整的堆栈跟踪。在 C# 中这很容易,但是在 Python 中我该怎么做呢?
例如。在 C# 中,我会做这样的事情:
try
{
ProcessFile(filePath);
}
catch (Exception ex)
{
throw new ApplicationException("Failed to process file " + filePath, ex);
}
在 Python 中我可以做类似的事情:
try:
ProcessFile(filePath)
except Exception as e:
raise Exception('Failed to process file ' + filePath, e)
...但这会丢失内部异常的回溯!
编辑:我想查看异常消息和堆栈跟踪,并将两者关联起来。也就是说,我想在输出中看到这里发生了异常 X,然后那里发生了异常 Y——就像我在 C# 中一样。这在 Python 2.6 中可行吗?看起来到目前为止我能做的最好的事情(基于 Glenn Maynard 的回答)是:
try:
ProcessFile(filePath)
except Exception as e:
raise Exception('Failed to process file' + filePath, e), None, sys.exc_info()[2]
这包括消息和回溯,但它不显示在回溯中发生的异常。
【问题讨论】:
-
接受的答案已经过时了,也许你应该考虑接受另一个。
-
@AaronHall 不幸的是 OP 自 2015 年以来就没有出现过。
标签: python exception error-handling