353

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)

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
Eva611
  • 5,964
  • 8
  • 30
  • 38

1 Answers1

558

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)

vartec
  • 131,205
  • 36
  • 218
  • 244
  • 133
    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 Sep 25 '13 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. – Rolf of Saxony Dec 04 '15 at 14:00
  • 7
    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 Feb 06 '18 at 19:08
  • 1
    You perhaps want to do something with `e` also since you give it a name :) – HelloGoodbye Mar 25 '20 at 00: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](https://stackoverflow.com/a/36755323/5127304). – Elias Aug 13 '21 at 10:53