How do you catch multiple different exceptions in Python and handle each of them differently?

Experience Level: Junior
Tags: Python

Answer

Use try/except block. In the except block define the type of exception that you want to catch. Use one except block for handling one exception. Sort the except blocks from the most specific at the top to the most generic at the bottom.

Example:

def my_method():
    try:
        int("This will cause exception to be raised")
    except ValueException:
        print("Your value is not a number.")
    except Exception:
        print("Something went seriously wrong.")

Python for beginners
Python for beginners

Are you learning Python ? Try our test we designed to help you progress faster.

Test yourself