Skip to content

Python multiple exceptions in one line

  • by

Use try-except blocks to catch multiple exceptions in one line in Python. An except clause may name multiple exceptions as a parenthesized tuple, for example:-

except (IDontLikeYouException, YouAreBeingMeanException) as e:
    pass

Python multiple exceptions in one line example

Simple example code of Multiple exceptions as a parenthesized tuple.

try:
    name = 'Bob'
    name += 5
except (NameError, TypeError) as error:
    print(error)
    rollbar.report_exc_info()

Output:

Python multiple exceptions in one line

How to catch multiple exceptions at once and deal with an individual one.

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()

This is because every exception in python is a child of built-in Exception class of python.

try:
    # anything you have to do
except Exception as e:
    if type(e) == EOFError:
        # do what is necessary
    elif type(e) == FileNotFoundError
        # do what is necessary

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