Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 787
Eva611 Avatar asked Oct 16 '22 15:10

Eva611


People also ask

Can one try have multiple except in Python?

According to the Python Documentation: A try statement may have more than one except clause, to specify handlers for different exceptions. At most one handler will be executed. In this example, we have two except clauses.

Can I catch multiple exception types on the same except branch?

As of Python 3.11 you can take advantage of the except* clause that is used to handle multiple exceptions. PEP-654 introduced a new standard exception type called ExceptionGroup that corresponds to a group of exceptions that are being propagated together. The ExceptionGroup can be handled using a new except* syntax.

Can one block of except statements handle multiple exception Python?

Can one block of except statements handle multiple exception? Answer: a Explanation: Each type of exception can be specified directly. There is no need to put it in a list.


1 Answers

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)

like image 508
vartec Avatar answered Oct 19 '22 04:10

vartec