Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I understand you can do multiple exceptions handling in this way

try:
    pass

except EOFError:
    deals_with_EOFError()

except FileNotFoundError:
    deals_with_FileNotFoundError()

But, I wanted to know how it could be done through something like this

try:
    pass
except (EOFError, FileNotFoundError):

    if EOFError:
        deals_with_EOFError()
    else:
        deals_with_FileNotFoundError()
like image 754
Risky Normal Avatar asked Sep 17 '25 14:09

Risky Normal


2 Answers

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()
like image 89
mrkre Avatar answered Sep 19 '25 05:09

mrkre


You can use type() function of python as follow:

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

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

like image 42
Mohammad Hossein Shojaeinia Avatar answered Sep 19 '25 05:09

Mohammad Hossein Shojaeinia