Python: One Try Multiple Except

In Python, is it possible to have multiple except statements for a single try ? For example:

 try: #something1 #something2 except something1: #return xyz except something2: #return abc 
+68
python syntax exception-handling
May 23 '11 at 10:07
source share
1 answer

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: handle_all_other_exceptions() 

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

The "as" keyword is used to assign an error to a variable so that it can be examined in more detail later in the code. Also note that parentheses for the case of a triple exception are necessary in python 3. There is additional information on this page: Capture multiple exceptions on one line (except block)

+141
May 23 '11 at 10:13
source share



All Articles