Adding information to an exception?

前端 未结 9 1825
-上瘾入骨i
-上瘾入骨i 2020-12-02 06:49

I want to achieve something like this:

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

def bar(arg1):
    try:
       foo()
             


        
9条回答
  •  被撕碎了的回忆
    2020-12-02 07:45

    Assuming you don't want to or can't modify foo(), you can do this:

    try:
        raise IOError('stuff')
    except Exception as e:
        if len(e.args) >= 1:
            e.args = (e.args[0] + ' happens',) + e.args[1:]
        raise
    

    This is indeed the only solution here that solves the problem in Python 3 without an ugly and confusing "During handling of the above exception, another exception occurred" message.

    In case the re-raising line should be added to the stack trace, writing raise e instead of raise will do the trick.

提交回复
热议问题