Python中的“内部异常”(带有追溯)?
问题内容:
我的背景是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]
这既包括消息,也包括回溯,但没有显示回溯中哪个异常发生。
问题答案:
Python 2
这很简单; 将回溯作为第三个引发的参数。
import sys
class MyException(Exception): pass
try:
raise TypeError("test")
except TypeError, e:
raise MyException(), None, sys.exc_info()[2]
捕获一个异常并重新引发另一个异常时,请务必执行此操作。