Adding information to an exception?

前端 未结 9 1819
-上瘾入骨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:54

    I don't like all the given answers so far. They are still too verbose imho. In either code and message output.

    All i want to have is the stacktrace pointing to the source exception, no exception stuff in between, so no creation of new exceptions, just re-raising the original with all the relevant stack frame states in it, that led there.

    Steve Howard gave a nice answer which i want to extend, no, reduce ... to python 3 only.

    except Exception as e:
        e.args = ("Some failure state", *e.args)
        raise
    

    The only new thing is the parameter expansion/unpacking which makes it small and easy enough for me to use.

    Try it:

    foo = None
    
    try:
        try:
            state = "bar"
            foo.append(state)
    
        except Exception as e:
            e.args = ("Appending '"+state+"' failed", *e.args)
            raise
    
        print(foo[0]) # would raise too
    
    except Exception as e:
        e.args = ("print(foo) failed: " + str(foo), *e.args)
        raise
    

    This will give you:

    Traceback (most recent call last):
      File "test.py", line 6, in 
        foo.append(state)
    AttributeError: ('print(foo) failed: None', "Appending 'bar' failed", "'NoneType' object has no attribute 'append'")
    

    A simple pretty-print could be something like

    print("\n".join( "-"*i+" "+j for i,j in enumerate(e.args)))
    

提交回复
热议问题