Python language basics 59: catching multiple exception types


In the previous post we looked at how to handle exceptions in python. The most important keywords you’ll need to know of are “try” and “except”. We saw how code execution stops at the point where the exception is raised. It continues on the first line of a matching except-block, i.e. which handles just that type of exception that was raised.

This short post shows a little trick if you want to handle different types of exception in the same way.

Multiple error types

We actually saw an example of catching multiple exception types in the previous post:

    //some code
except KeyError:
    print("This capital doesn't figure in the collection")
except ZeroDivisionError:
    print("Errr..., what are you doing???")

What if you want to carry out the same exception handling logic irrespective of the exception type? You could write like this:

    //some code
except KeyError:
except ZeroDivisionError:

However, it’s futile, as the same logic is duplicated in the two different places. You can solve the issue as follows:

except (KeyError, ZeroDivisionError):

You can just list the different exception types and separate them by a comma in parenthesis.

In case you’d like to handle any type of exception then you’ll find several tips on the internet, such as this thread:

except Exception:

However, you should not overuse this in real code. Always try to catch specific exceptions first and only then have a generic exception handling block so that your application doesn’t just exit unexpectedly.

Read the next part here.

Read all Python-related posts on this blog here.


About Andras Nemes
I'm a .NET/Java developer living and working in Stockholm, Sweden.

2 Responses to Python language basics 59: catching multiple exception types

  1. Pingback: Python language basics 59: catching multiple exception types | Dinesh Ram Kali.

  2. Pingback: Python language basics 60: interrogating the exception | Dinesh Ram Kali.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Elliot Balynn's Blog

A directory of wonderful thoughts

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog


Once Upon a Camayoc

Bite-size insight on Cyber Security for the not too technical.

%d bloggers like this: