Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: How to ignore an exception and proceed? [duplicate]

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?

like image 237
The.Anti.9 Avatar asked Feb 22 '09 11:02

The.Anti.9


People also ask

How do you use try without except in Python?

We cannot have the try block without except so, the only thing we can do is try to ignore the raised exception so that the code does not go the except block and specify the pass statement in the except block as shown earlier. The pass statement is equivalent to an empty line of code. We can also use the finally block.


2 Answers

except Exception:     pass 

Python docs for the pass statement

like image 192
Andy Hume Avatar answered Sep 20 '22 12:09

Andy Hume


Generic answer

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

try:     do_something() except Exception:     pass 

Using except Exception instead of a bare except avoid catching exceptions like SystemExit, KeyboardInterrupt etc.

Python 2

Because of the last thrown exception being remembered in Python 2, 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.

Python 3

In Python 3, the variable that holds the exception instance gets deleted on exiting the except block. Even if the variable held a value previously, after entering and exiting the except block it becomes undefined again.

like image 40
tzot Avatar answered Sep 18 '22 12:09

tzot