How to Catch Multiple Exceptions in Python

How to Catch Multiple Exceptions in Python

by Ian Eyre Reading time estimate 26m intermediate best-practices python

In this tutorial, you’ll learn various techniques to catch multiple exceptions with Python. To begin with, you’ll review Python’s exception handling mechanism before diving deeper and learning how to identify what you’ve caught, sometimes ignore what you’ve caught, and even catch lots of exceptions.

Python raises an exception when your code encounters an occasional but not unexpected error. For example, this will occur if you try to read a missing file. Because you’re aware that such exceptions may occur, you should write code to deal with, or handle, them. In contrast, a bug happens when your code does something illogical, like a miscalculation. Bugs should be fixed, not handled. This is why debugging your code is important.

When your Python program encounters an error and raises an exception, your code will probably crash, but not before providing a message within a traceback indicating what the problem is:

Language: Python
>>> 12 / "five"
Traceback (most recent call last):
  ...
TypeError: unsupported operand type(s) for /: 'int' and 'str'

Here, you’ve tried to divide a number by a string. Python can’t do this, so it raises a TypeError exception. It then shows a traceback reminding you that the division operator doesn’t work with strings.

To allow you to take action when an error occurs, you implement exception handling by writing code to catch and deal with exceptions. Better this than your code crashing and scaring your user. To handle exceptions, you use the try statement. This allows you to monitor code for exceptions and take action should they occur.

Most try statements use tryexcept blocks as follows:

  • The try block contains the code that you wish to monitor for exceptions. Any exceptions raised within try will be eligible for handling.

  • One or more except blocks then follow try. These are where you define the code that will run when exceptions occur. In your code, any raised exceptions trigger the associated except clause. Note that where you have multiple except clauses, your program will run only the first one that triggers and then ignore the rest.

To learn how this works, you write a try block to monitor three lines of code. You include two except blocks, one each for ValueError and ZeroDivisionError exceptions, to handle them should they occur:

Language: Python
# handler_statement.py

try:
    first = float