Try instruction syntax

I read the python documentation , can anyone help me with an interpretation of this?

try_stmt ::= try1_stmt | try2_stmt try1_stmt ::= "try" ":" suite ("except" [expression [("as" | ",") identifier]] ":" suite)+ ["else" ":" suite] ["finally" ":" suite] try2_stmt ::= "try" ":" suite "finally" ":" suite 

I initially thought it meant that try statements should have either formats

  • try And finally or
  • try , except , else AND finally .

But after reading the documentation, he mentioned that else is optional, and therefore finally . So, I was wondering what the documentation is for, showing us the code in the above format?

+7
python
source share
1 answer

You do have two forms of the try . The main difference between the two is that in the case of try1_stmt , the except try1_stmt must be specified .

In Introduction | Python language reference designator , the following is written:

A star (*) means zero or more repetitions of the previous paragraph; likewise, plus (+) means one or more repetitions , and a phrase enclosed in square brackets ([]) means zero or one case (in other words, the attached phrase is optional). The operators * and + are bound as closely as possible; parentheses are used to group .

So, in particular, in the first form:

 try1_stmt ::= "try" ":" suite ("except" [expression [("as" | ",") identifier]] ":" suite)+ ["else" ":" suite] ["finally" ":" suite] 

The else and finally else are optional ([]) , you only need the try and one or more (+) except articles.

In the second form:

 try2_stmt ::= "try" ":" suite "finally" ":" suite 

You only have one try and one finally clause with no except clauses.


Note that for the first case, the order of the else and finally clauses is fixed. The else clause following the finally clause raises a SyntaxError .

At the end of the day, it all boils down to the fact that you cannot have a try clause with only an else clause. Thus, in code form, these two are allowed:

The first form of the try statement ( try1_stmt ):

 try: x = 1/0 except ZeroDivisionError: print("I'm mandatory in this form of try") print("Handling ZeroDivisionError") except NameError: print("I'm optional") print("Handling NameError") else: print("I'm optional") print("I execute if no exception occured") finally: print("I'm optional") print("I always execute no matter what") 

The second form ( try2_stmt ):

 try: x = 1/0 finally: print("I'm mandatory in this form of try") print("I always execute no matter what") 

For an easy-to-read PEP on this subject, see PEP 341 , which contains the original sentence for two forms of try .

+4
source share

All Articles