views:

3449

answers:

3

I have a try...except block in my code and When an exception is throw. I really just want to continue with the code because in that case, everything is still able to run just fine. The problem is if you leave the except: block empty or with a #do nothing, it gives you a syntax error. I can't use continue because its not in a loop. Is there a keyword i can use that tells the code to just keep going?

+22  A: 
except:
    pass
Andy Hume
except Exception: pass # important not to swallow other exceptions!
Roger Pate
This. This is the worst code.
Aaron Gallagher
@Aaron - I agree, but the question wasn't if this was a good/bad idea
David
This will catch SystemExit, KeyboardInterrupt and other things that you probably don't want to catch.
FogleBird
+8  A: 

Try this:

try:
    blah()
except:
    pass
ryeguy
+7  A: 

The standard "nop" in Python is the pass statement:

try:
    do_something()
except Exception:
    pass

Because of the last thrown exception being remembered in Python, some of the objects involved in the exception-throwing statement are being kept live indefinitely (actually, until the next exception). In case this is important for you and (typically) you don't need to remember the last thrown exception, you might want to do the following instead of pass:

try:
    do_something()
except Exception:
    sys.exc_clear()

This clears the last thrown exception.

ΤΖΩΤΖΙΟΥ