Skip to content

Python multiple exceptions

  • by

You can define multiple exceptions with the same except clause to catch multiple exceptions in Python. If the Python interpreter finds a matching exception, then it’ll execute the code written under except clause.

Except(Exception1, Exception2,…ExceptionN) as e:

Or use multiple except blocks.

try:
my_function(x)
except AttributeError:
# Do something
...
except (ValueError, TypeError):
# Do something else
...

Python multiple exceptions example

Simple example code uses the ‘except’ clause with multiple exceptions in Python.

import sys

try:
    d = 8
    d = d + '5'

except(TypeError, SyntaxError, AttributeError, ZeroDivisionError) as e:
    print(e)

Output:

Python multiple exceptions example

Python catches different types of exceptions

try:
    # defining variables
    a = 10
    b = 0
    c = "abc"
    # adding the variables
    d = a + c
# Zerodivision error
except ZeroDivisionError:
    # printing error
    print("Zero Division Error occurs")
# index error
except IndexError:
    # printing
    print("Index error occurs")
# type error
except TypeError:
    # printing
    print("Type error occurs")

Output: Type error occurs

Do comment if you have any doubts or suggestions on this Python exception-handling topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Your email address will not be published. Required fields are marked *