567

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?

Rob
  • 47,999
  • 5
  • 74
  • 91
The.Anti.9
  • 43,474
  • 48
  • 123
  • 161

4 Answers4

828
except Exception:
    pass

Python docs for the pass statement

mit
  • 11,083
  • 11
  • 50
  • 74
Andy Hume
  • 40,474
  • 10
  • 47
  • 58
  • 96
    except Exception: pass # important not to swallow other exceptions! –  Feb 22 '09 at 16:46
  • 29
    This will catch SystemExit, KeyboardInterrupt and other things that you probably don't want to catch. – FogleBird Jan 02 '10 at 01:13
  • 2
    It won't catch KeyboardInterrupt. For example: `while True:` `try: `f = open('filedoesnotexist.txt')` `except:` `pass` KeyboardInterrupt stops and exits the code. – Chthonic Project Jul 24 '12 at 15:59
  • 19
    @ChthonicProject a bare `except` will catch any exception, including a KeyboardInterrupt, but only if it happens inside the `try`. In your example there, a KeyboardInterrupt can occur before the `try` or inside the `except`, where it won't be caught. If you run an example like `while True:` `try: pass` `except: pass`, you'll find that the KeyboardInterrupt gets caught just about 50% of the time. If you `time.sleep(1)` inside the `try`, you'll find that it gets caught almost every time. – Jack O'Connor Mar 22 '13 at 08:39
  • 1
    This stops executing after the first exception. What I just want to totally ignore all exceptions, eg `print('this'); 1/0; print('this too');`? And say I have 10 commands, don't want to write 10 try except pass blocks. – citynorman Nov 02 '18 at 00:46
  • One also can use `...` (ellipsis) in `except` clause instead of `pass`: `except: ...` – Andrey Semakin Mar 12 '19 at 14:23
  • `…` is just an expression like `1` or `True` or `None` or `NotImplemented`, all of which can be used as quasi-nops (and `pass` still beats them because it produces exactly 0 (zero) opcodes for the Python VM to execute (in CPython that is)). – tzot Jul 15 '20 at 23:56
  • How does this compare to try: xxx() finally: pass? – perreal Feb 04 '21 at 16:54
338

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.

tzot
  • 92,761
  • 29
  • 141
  • 204
  • 47
    This is a better answer than the one that was accepted because it uses "except Exception:" instead of just "except:" which as others have pointed out will improperly swallow other things that you don't want to catch like SystemExit and KeyboardInterrupt. – aculich Jul 11 '11 at 21:50
  • 4
    +1 It also clears the error which is important when running unittests and expecting exceptions – geographika Oct 26 '11 at 13:50
  • 7
    Note that `exc_clear` was removed in python 3. https://docs.python.org/3/whatsnew/3.0.html#index-22. For some ways to address this in Python 3 see here: https://cosmicpercolator.com/2016/01/13/exception-leaks-in-python-2-and-3/ – bcattle Mar 06 '18 at 18:59
  • See https://stackoverflow.com/a/53575187/3140992 for quickly ignoring multiple exceptions – citynorman Dec 01 '18 at 21:26
  • 1
    One also can use `...` (ellipsis) in `except` clause instead of `pass`: `except Exception: ...` – Andrey Semakin Mar 12 '19 at 14:25
292

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.

Jack O'Connor
  • 10,068
  • 4
  • 48
  • 53
  • 2
    I'm not sure I like this solution... I guess the idea is we've replaced 3 lines with just 1 (the try, except, and pass are all merged into one.) The main thing I object to is how this introduces a new keyword that seems to vindicate something you probably shouldn't be doing... it seems like you should always at least log exceptions you're catching... – ArtOfWarfare Oct 14 '13 at 13:13
  • When an exception is raised will it continue the code after the try/catch or whatever is outside of the `with` block? – Mikhail Nov 13 '13 at 07:45
  • 5
    This is equivalent to wrapping your code in a `try...catch: pass`, so if an exception is raised inside the block, execution will continue after the end of the block. – Jack O'Connor Nov 14 '13 at 08:45
  • 2
    @ArtOfWarfare What if I said, I'll give you an integer, but sometimes I'll give it to you in a singleton tuple, and I won't tell you when I do one or the other; now your job is to always give me back the integer? Perhaps you would appreciate being able to write something like `with suppress(TypeError): return data[0]` (longer example: http://pastebin.com/gcvAGqEP) – Air May 02 '14 at 21:03
  • @Navin Python can't just pretend that an exception didn't exist. Suppose I have a statement like `y = f(x) * g(x)`, and then `f(x)` raises an exception. Even if Python ignores it, `f(x)` never returns a value, so there's no way for Python to assign a value to `y`. The designers could've said "assume a value of None" or "skip statements containing any expression that failed to evaluate," but that would end up being very confusing. Using `try` blocks to group statements that fail together keeps things simple. – Jack O'Connor Jan 14 '15 at 17:14
  • @JackO'Connor Fair enough. I was hoping there would be a way to replace an expressions with None if it raises an exception. – Navin Jan 14 '15 at 18:07
  • Can it be done inline? For instance something like `supress(myFunc, suppressedException, returnValueOnFailure)`? – jeromej Jun 23 '15 at 01:43
  • @JeromeJ you can't do that with `suppress` directly, because it's a context manager. (For details about how context managers work, see here: https://docs.python.org/3.4/library/stdtypes.html#typecontextmanager) But it would be pretty simple to define your own `callCatchingExceptions` function that used `suppress` or an ordinary `try` block on the inside, if you wanted. – Jack O'Connor Jun 24 '15 at 14:01
  • 9
    FYI, django revert the use of `with suppress(Exception)` on 2017-09 , because try/except performs better. Check this commits [Reverted "Fixed #27818 -- Replaced try/except/pass with contextlib.su…](https://github.com/django/django/commit/6e4c6281dbb7ee12bcdc22620894edb4e9cf623f) – stackoverYC Nov 07 '17 at 07:00
27

Try this:

try:
    blah()
except:
    pass
ryeguy
  • 65,519
  • 58
  • 198
  • 260