SirDeimos
SirDeimos

Reputation: 93

Python raise exception within nested try

I've got a nested try/except block in a try, and I'd like to raise the error and then break from the method, but it continues on.

try:
    #stuff
    try:
        #do some stuff
    except:
        raise CustomException('debug info')
    #do some more stuff
except CustomException:
    #stuff
#do even more stuff
return stuff

Currently, after it raises the CustomException (line 5), it then jumps to the except (line 7) and then continues on and eventually does the return. I'd like it to break when it raises, but not get caught by the except. It still needs to catch the CustomException if it happens in '#do some more stuff' and continue on.

Upvotes: 0

Views: 1171

Answers (2)

KurzedMetal
KurzedMetal

Reputation: 12946

Simply writing raise, re-raises the catched exception.

try:
    #stuff
    try:
        #do some stuff
    except:
        raise CustomException('debug info')
    #do some more stuff
except CustomException:
    #stuff
    raise  ## KM: This re-raise the exception

## KM: This wont be executed if CustomException('debug info') was raised
#do even more stuff

return stuff

Upvotes: 2

falsetru
falsetru

Reputation: 369094

How about change the structure of try-except as follow?

try:
    #do some stuff
except:
    raise CustomException('debug info')
try:
    #do some more stuff
except CustomException:
    #stuff
#do even more stuff
return stuff

Upvotes: 2

Related Questions