Eva611
Eva611

Reputation: 6204

One try block with multiple excepts

In Python, is it possible to have multiple except statements for one try statement? Such as:

try:
    #something1
    #something2
except ExceptionType1:
    #return xyz
except ExceptionType2:
    #return abc

For the case of handling multiple exceptions the same way, see Catch multiple exceptions in one line (except block)

Upvotes: 373

Views: 270625

Answers (2)

Bhavin Desai
Bhavin Desai

Reputation: 1

Nested try except could work too.

I found the above solution was hard to implement and I just had a single extra exception.

try:
    1/0
except:
    try:
        1/0
    except:
        1/1

Upvotes: -1

vartec
vartec

Reputation: 134711

Yes, it is possible.

try:
   ...
except FirstException:
   handle_first_one()

except SecondException:
   handle_second_one()

except (ThirdException, FourthException, FifthException) as e:
   handle_either_of_3rd_4th_or_5th()

except Exception:
   handle_all_other_exceptions()

See: http://docs.python.org/tutorial/errors.html

The "as" keyword is used to assign the error to a variable so that the error can be investigated more thoroughly later on in the code. Also note that the parentheses for the triple exception case are needed in python 3. This page has more info: Catch multiple exceptions in one line (except block)

Upvotes: 584

Related Questions