4

I'm trying to do a nested try/catch block in Python to print some extra debugging information:

try:
    assert( False )
except:
    print "some debugging information"
    try:
        another_function()
    except:
        print "that didn't work either"
    else:
        print "ooh, that worked!"
    raise

I'd like to always re-raise the first error, but this code appears to raise the second error (the one caught with "that didn't work either"). Is there a way to re-raise the first exception?

1
  • what are you trying to do ? Commented Oct 1, 2013 at 4:10

3 Answers 3

3

raise, with no arguments, raises the last exception. To get the behavior you want, put the error in a variable so that you can raise with that exception instead:

try:
    assert( False )
# Right here
except Exception as e:
    print "some debugging information"
    try:
        another_function()
    except:
        print "that didn't work either"
    else:
        print "ooh, that worked!"
    raise e

Note however that you should capture for a more specific exception rather than just Exception.

Sign up to request clarification or add additional context in comments.

Comments

2

You should capture the first Exception in a variable.

try:
    assert(False)
except Exception as e:
    print "some debugging information"
    try:
        another_function()
    except:
        print "that didn't work either"
    else:
        print "ooh, that worked!"
    raise e

raise by default will raise the last Exception.

Comments

0

raise raises the last exception caught unless you specify otherwise. If you want to reraise an early exception, you have to bind it to a name for later reference.

In Python 2.x:

try:
    assert False
except Exception, e:
    ...
    raise e

In Python 3.x:

try:
    assert False
except Exception as e:
    ...
    raise e

Unless you are writing general purpose code, you want to catch only the exceptions you are prepared to deal with... so in the above example you would write:

except AssertionError ... :

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.