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