In this article we're going to be taking a look at the try/except clause, and specifically how you can catch multiple exceptions in a single line, as well as how to use the
Both of these techniques will help you in writing more accessible and versatile code that adheres to DRY (don't repeat yourself) principles.
Let's start by looking at the problem:
try: do_the_thing() except TypeError as e: do_the_other_thing() except KeyError as e: do_the_other_thing() except IndexError as e: do_the_other_thing()
As we can see, this is very WET code, we repeat the same invocation multiple times. Practices like this can make our code's reading and refactoring a living nightmare.
Rather than writing exceptions one after another, wouldn't it be better to group all of these exception handlers into a single line?
If you're just here for a quick answer, it's simple: use a tuple.
All the errors contained in the exception line tuple will be evaluated together:
try: do_the_thing() except (TypeError, KeyError, IndexError) as e: do_the_other_thing()
Avoiding Bad Practices
"Errors should never pass silently." - The Zen of Python.
try/except clauses are probably the most misused pattern in Python.
Used improperly, they end up being the cliché of drunks and lampposts, being used only when the Python interpreter starts caroling the "12 Errors of Christmas".
It's very tempting to just put a
try and a bare exception on a problem to "make it go away". By doing that, we're effectively sweeping the exceptions under the rug, which is a shame, especially since they can be wonderfully helpful in recovering from potentially fatal errors, or shining a light on hidden bugs.
That's why when using except clauses you should always be sure to specify the errors you know you could encounter, and exclude the ones you don't.
Letting your program fail is okay, even preferred, to just pretending the problem doesn't exist.
"Errors should never pass silently... unless explicitly silenced."
Free eBook: Git Essentials
Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!
However, once in a blue moon when you do get the opportunity to ignore exception handling, you can use
from contextlib import suppress with suppress(TypeError, KeyError, IndexError): do_the_thing()
suppress() method takes a number of exceptions as its argument, and performs a try/except/pass with those errors. As you can see it also lets you write multiple exceptions in a single line.
This let's you avoid writing a try/except/pass manually:
try: do_the_thing() except (TypeError, KeyError, IndexError) as e: pass
Better yet, it's also standard in any version of Python 3.4 and above!
In this article, we've covered how to handle multiple exceptions in a single line. We've also briefly gone over some bad practices of ignoring exceptions, and used the
suppress() function to suppress exceptions explicitly.