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
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
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)
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0