ChatGPT解决这个技术问题 Extra ChatGPT

Python: One Try Multiple Except

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
@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.

v
vartec

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)


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.
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.
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)
You perhaps want to do something with e also since you give it a name :)
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.