Python: How to ignore an exception and proceed?
This question already has an answer here:
except:
pass
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.
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.
下一篇: Python:如何忽略异常并继续?