The Python Oracle

Python: How to ignore an exception and proceed?

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Future Grid Looping

--

Chapters
00:00 Question
00:40 Accepted answer (Score 801)
00:52 Answer 2 (Score 328)
02:13 Answer 3 (Score 281)
03:03 Answer 4 (Score 25)
03:15 Thank you

--

Full question
https://stackoverflow.com/questions/5747...

Accepted answer links:
[Python docs for the pass statement]: https://docs.python.org/3.7/tutorial/con...

Answer 3 links:
http://hg.python.org/cpython/rev/406b47c...
[http://www.youtube.com/watch?v=OSGv2VnC0...]: http://www.youtube.com/watch?

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #exception

#avk47



ACCEPTED ANSWER

Score 857


except Exception:
    pass

Python docs for the pass statement




ANSWER 2

Score 348


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.




ANSWER 3

Score 310


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: http://hg.python.org/cpython/rev/406b47c64480

And here's the author, Raymond Hettinger, talking about this and all sorts of other Python hotness (relevant bit at 43:30): http://www.youtube.com/watch?v=OSGv2VnC0go

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.




ANSWER 4

Score 29


Try this:

try:
    blah()
except:
    pass