369

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)

0

1 Answer 1

579

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)

5
  • 141
    If you want to do the same thing in both cases, it's except (SomeError, OtherError):. Doesn't answer the OP question, but might help some people who get here through Google.
    – Mark
    Commented Sep 25, 2013 at 14:43
  • If for example you have to convert multiple versions of a data structure to a new structure, when updating versions of code for example, you can nest the try..excepts. Commented Dec 4, 2015 at 14:00
  • 8
    If you want to handle all exceptions you should be using except Exception: instead of plain except:. (Plain except will catch even SystemExit and KeyboardInterrupt which usually is not what you want)
    – polvoazul
    Commented Feb 6, 2018 at 19:08
  • 2
    You perhaps want to do something with e also since you give it a name :) Commented Mar 25, 2020 at 0:21
  • If you just one to avoid getting error without handling specific exceptions, you can write nested levels of try/except as mentioned also in this answer.
    – Elias
    Commented Aug 13, 2021 at 10:53

Not the answer you're looking for? Browse other questions tagged or ask your own question.