Skip to content

Python catch multiple exceptions

  • by

Use try-except blocks to catch multiple exceptions or single exceptions in Python. In cases where a process raises more than one possible exception, they can all be handled using a single except clause.

try:
    ...
except RuntimeError:
    print err1
except NameError:
    print err2

...

Python catch multiple exceptions

Simple example code and approaches for handling multiple exceptions in Python.

Using Same Code Block

Catch two types of exceptions TypeError and ValueError.

s = input()

try:
    num = int(input())
    print(s + num)
except (TypeError, ValueError) as e:
    print(e)

Output:

Python catch multiple exceptions

Using Different Code Blocks

NameError and TypeError exceptions handled differently on their own except blocks.

s = input()

try:
    num = int(input())
    print(s + num)
except TypeError as te:
    print(te)
except NameError as ne:
    print(ne)

How to catch multiple exceptions at once and deal with individual one, in Python?

Answer: You can use built-in type() to determine the type of the error object.

try:
    pass
except (EOFError, FileNotFoundError) as e:
    if type(e) is EOFError:
        deals_with_EOFError()
    else:
        deals_with_FileNotFoundError()

However, your initial example has better readability.

try:
    pass
except EOFError:
    deals_with_EOFError()
except FileNotFoundError:
    deals_with_FileNotFoundError()

Output: stackoverflow.com

Do comment if you have any doubts or suggestions on this Python exception 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

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading