“内部例外” (跟踪)在Python中? [英] "Inner exception" (with traceback) in Python?

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

问题描述

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



在C#中,我会这样做:

  try 
{
ProcessFile(filePath);
}
catch(Exception ex)
{
抛出新的ApplicationException(无法处理文件+ filePath,ex);
}

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

  try:
ProcessFile(filePath)
除了异常作为e:
raise异常('无法处理文件'+ filePath ,e)

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



编辑:我想同时看到异常消息和两个堆栈跟踪,并将两者关联起来。也就是说,我想在输出中看到异常X发生在这里,然后异常Y在那里 - 与C#中一样。这是否可能在Python 2.6中?看起来像我最近可以做的(基于Glenn Maynard的答案)是:

  try:
ProcessFile filePath)
除了异常作为e:
raise异常('无法处理文件'+ filePath,e),无,sys.exc_info()[2]

这包括消息和回溯两者,但它不显示在追溯中的哪个异常。

解决方案

很简单通过追溯作为第三个参数来提高。

  import sys 
class MyException(Exception):pass

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

在捕获一个例外并重新提起另一个异常时,请务必执行此操作。


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?

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

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

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!

Edit: 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.

解决方案

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天全站免登陆