Python: How to ignore an exception and proceed?


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?

Asked By: The.Anti.9



except Exception:

Python docs for the pass statement

Answered By: Andy Hume

Try this:

Answered By: ryeguy

Generic answer

The standard “nop” in Python is the pass statement:

except Exception:

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:

except Exception:

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.

Answered By: tzot

There’s a new way to do this coming in Python 3.4:

from contextlib import suppress

with suppress(Exception):
  # your code

Here’s the commit that added it:

And here’s the author, Raymond Hettinger, talking about this and all sorts of other Python hotness (relevant bit at 43:30):

If you wanted to emulate the bare except keyword and also ignore things like KeyboardInterrupt—though you usually don’t—you could use with suppress(BaseException).

Edit: Looks like ignored was renamed to suppress before the 3.4 release.

Answered By: Jack O'Connor
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.