Python: Catch Multiple Exceptions in One Line - Stack Abuse

Python: Catch Multiple Exceptions in One Line

Introduction

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 suppress() method.

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()

Brutal.

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?

Multiple Exceptions

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()

Easy, right?

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 start 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."

However, once in a blue moon when you do get the opportunity to ignore exception handling, you can use suppress():

Better understand your data with visualizations

  •  30-day no-questions refunds
  •  Beginner to Advanced
  •  Updated regularly (update June 2021)
  •  New bonus resources and guides
from contextlib import suppress

with suppress(TypeError, KeyError, IndexError):
    do_the_thing()

The 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 let's 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!

Conclusion

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 supress() function to supress exceptions explicitly.

Last Updated: January 19th, 2021

Improve your dev skills!

Get tutorials, guides, and dev jobs in your inbox.

No spam ever. Unsubscribe at any time. Read our Privacy Policy.

Spencer PorterAuthor

Full Stack Developer and Technical Writer.

I love writing about Python and React, and how anyone can create amazing products and tools.

Want a remote job?

    Prepping for an interview?

    • Improve your skills by solving one coding problem every day
    • Get the solutions the next morning via email
    • Practice on actual problems asked by top companies, like:
     
     
     

    Better understand your data with visualizations

    •  30-day no-questions refunds
    •  Beginner to Advanced
    •  Updated regularly (update June 2021)
    •  New bonus resources and guides

    © 2013-2021 Stack Abuse. All rights reserved.