258
votes

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
1
@Eva611: Don't apologize. (1) try it. (2) post an answer to your question. - S.Lott
It does work. Tried it with the python interpreter... - Eva611
@Eva611 I think your question was fine. Was much faster for me to Google this rather than setting up an example in the Python interpreter, so I was happy that you asked. DrTysa and others should have just responded with a quick "yes" rather than scolding you. - galarant
Most of the time your first guess is going to be wrong, or miss subtle nuances, so (like 15,000 others) I tried google first! - Chris
I tried google and found this question. Therefore, I'm glad someone else asked it in so public a forum as SO, and I'm glad enough other people linked to it that google's algorithm popped it up as my first result. - kingledion

1 Answers

411
votes

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)