“内部异常"(带回溯)在 Python 中? [英] "Inner exception" (with traceback) in Python?

查看:18
本文介绍了“内部异常"(带回溯)在 Python 中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

My background is in C# and I've just recently started programming in Python. When an exception is thrown I typically want to wrap it in another exception that adds more information, while still showing the full stack trace. It's quite easy in C#, but how do I do it in Python?

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

Eg. in C# I would do something like this:

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

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

In Python I can do something similar:

try:
  ProcessFile(filePath)
except Exception as e:
  raise Exception('Failed to process file ' + filePath, e)

...但这失去了内部异常的回溯!

...but this loses the traceback of the inner exception!

我想查看异常消息和堆栈跟踪并将两者关联起来.也就是说,我想在输出中看到异常 X 发生在这里,然后异常 Y 出现在那里——就像我在 C# 中所做的那样.这在 Python 2.6 中可能吗?看起来到目前为止我能做的最好的事情(基于 Glenn Maynard 的回答)是:

I'd like to see both exception messages and both stack traces and correlate the two. That is, I want to see in the output that exception X occurred here and then exception Y there - same as I would in C#. Is this possible in Python 2.6? Looks like the best I can do so far (based on Glenn Maynard's answer) is:

try:
  ProcessFile(filePath)
except Exception as e:
  raise Exception('Failed to process file' + filePath, e), None, sys.exc_info()[2]

这包括消息和回溯,但它没有显示哪个异常发生在回溯中.

This includes both the messages and both the tracebacks, but it doesn't show which exception occurred where in the traceback.

推荐答案

Python 2

很简单;将回溯作为第三个参数传递给 raise.

Python 2

It's simple; pass the traceback as the third argument to raise.

import sys
class MyException(Exception): pass

try:
    raise TypeError("test")
except TypeError, e:
    raise MyException(), None, sys.exc_info()[2]

在捕获一个异常并重新引发另一个异常时总是这样做.

Always do this when catching one exception and re-raising another.

这篇关于“内部异常"(带回溯)在 Python 中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆