向异常添加信息? [英] Adding information to an exception?

查看:145
本文介绍了向异常添加信息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编辑:我正在运行python 2.6

I am running python 2.6

我想要实现这样的东西:

I want to achieve something like this:

def foo():
   try:
       raise IOError('Stuff ')
   except:
       raise

def bar(arg1):
    try:
       foo()
    except Exception as e:
       e.message = e.message + 'happens at %s' % arg1
       raise

bar('arg1')



Traceback...
  IOError('Stuff Happens at arg1')

但是我得到的是:

Traceback..
  IOError('Stuff')

有关如何实现这一点的线索?

Any clues as to how to achieve this?

推荐答案

我会这样做,所以改变它的类型在 foo()不会还需要在 bar()中更改它。

I'd do it like this so changing its type in foo() won't require also changing it in bar().

def foo():
    try:
        raise IOError('Stuff')
    except:
        raise

def bar(arg1):
    try:
        foo()
    except Exception as e:
        raise type(e)(e.message + ' happens at %s' % arg1)

bar('arg1')



Traceback (most recent call last):
  File "test.py", line 13, in <module>
    bar('arg1')
  File "test.py", line 11, in bar
    raise type(e)(e.message + ' happens at %s' % arg1)
IOError: Stuff happens at arg1

更新1

这是一个稍微修改,保留原始的追溯:

Here's a slight modification that preserves the original traceback:

...
def bar(arg1):
    try:
        foo()
    except Exception as e:
        import sys
        raise type(e), type(e)(e.message +
                               ' happens at %s' % arg1), sys.exc_info()[2]

bar('arg1')



Traceback (most recent call last):
  File "test.py", line 16, in <module>
    bar('arg1')
  File "test.py", line 11, in bar
    foo()
  File "test.py", line 5, in foo
    raise IOError('Stuff')
IOError: Stuff happens at arg1

更新2

对于Python 3.x,我第一次更新中的代码在语法上不正确,加上有一个 BaseException 上的消息属性撤回到PEP 352的更改。所以目前,在Python 3.5.2中,无论如何,您需要沿着这些方向执行某些操作,以保留回溯,而不是在函数 bar()中对异常类型进行硬编码。另请注意,将有一行:

For Python 3.x, the code in my first update is syntactically incorrect plus the idea of having a message attribute on BaseException was retracted in a change to PEP 352 on 2012-05-16 (my first update was posted on 2012-03-12). So currently, in Python 3.5.2 anyway, you'd need to do something along these lines to preserve the traceback and not hardcode the type of exception in function bar(). Also note that there will be the line:

During handling of the above exception, another exception occurred:

显示回溯消息。

# for Python 3.x
...
def bar(arg1):
    try:
        foo()
    except Exception as e:
        import sys
        raise type(e)(str(e) +
                      ' happens at %s' % arg1).with_traceback(sys.exc_info()[2])

bar('arg1')

更新3

一个评论者问是否有一种可以在Python 2和3中工作的方法。尽管答案可能似乎是否,由于语法差异,的方式,通过使用帮助函数,如 reraise() ypi / six /rel =noreferrer> 6 附加模块。所以,如果你不想因为某些原因使用这个库,下面是一个简化的独立版本。

A commenter asked if there was a way that would work in both Python 2 and 3. Although the answer might seem to be "No" due to the syntax differences, there is a way around that by using a helper function like reraise() in the six add-on module. So, if you'd rather not use the library for some reason, below is a simplified standalone version.

注意,由于异常在 reraise()函数,这将出现在任何追溯中,但最终的结果是你想要的。

Note too, that since the exception is reraised within the reraise() function, that will appear in whatever traceback is raised, but the final result is what you want.

import sys

if sys.version_info[0] < 3:  # Python 2?
    # using exec avoids a SyntaxError in Python 3
    exec("""def reraise(exc_type, exc_value, exc_traceback=None):
                raise exc_type, exc_value, exc_traceback""")
else:
    def reraise(exc_type, exc_value, exc_traceback=None):
        if exc_value is None:
            exc_value = exc_type()
        if exc_value.__traceback__ is not exc_traceback:
            raise exc_value.with_traceback(exc_traceback)
        raise exc_value

def foo():
    try:
        raise IOError('Stuff')
    except:
        raise

def bar(arg1):
    try:
       foo()
    except Exception as e:
        reraise(type(e), type(e)(str(e) +
                                 ' happens at %s' % arg1), sys.exc_info()[2])

bar('arg1')

这篇关于向异常添加信息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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