相关疑难解决方法(0)

Python中的"内部异常"(带回溯)?

我的背景是在C#中,我刚刚开始用Python编程.抛出异常时,我通常希望将其包装在另一个添加更多信息的异常中,同时仍然显示完整的堆栈跟踪.在C#中它很容易,但我如何在Python中完成它?

例如.在C#我会做这样的事情:

try
{
  ProcessFile(filePath);
}
catch (Exception ex)
{
  throw new ApplicationException("Failed to process file " + filePath, ex);
}
Run Code Online (Sandbox Code Playgroud)

在Python中我可以做类似的事情:

try:
  ProcessFile(filePath)
except Exception as e:
  raise Exception('Failed to process file ' + filePath, e)
Run Code Online (Sandbox Code Playgroud)

......但这会失去内部异常的追溯!

编辑:我想看到两个异常消息和两个堆栈跟踪并将两者关联起来.也就是说,我想在输出中看到异常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]
Run Code Online (Sandbox Code Playgroud)

这包括消息和两个回溯,但它不会显示回溯中发生的异常.

python error-handling exception

131
推荐指数
6
解决办法
3万
查看次数

标签 统计

error-handling ×1

exception ×1

python ×1