0

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.

2
  • You are basically raising an exception and immediately catching it. It makes no sense, of course it will continue. If you want to "break from the method" you have to let the Exception to leave from your method, not catching it. Commented Aug 7, 2014 at 14:04
  • How about using different exception classes? Commented Aug 7, 2014 at 14:08

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

Comments

2

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

2 Comments

Whoops, forgot to add a #do stuff
@SirDeimos, I have no idea except 3 try-except blocks for stuff, do some stuff, do some more stuff.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.