尝试语句语法
我一直在阅读python文档,有人可以帮我解释这个吗?
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
我最初认为这意味着尝试声明必须具有任何格式
try finally或 try , except , else与finally 。 但在阅读文档后,它提到了else是可选的, finally也是如此。 所以,我想知道文档的目的是什么,向我们展示了以上述格式的代码开始?
你有两种形式的try声明。 它们之间的主要区别在于,在try1_stmt的情况下必须指定 except子句。
在介绍| Python语言参考的符号如下:
星号(*)表示前面项目的零次或多次重复 ; 同样, 加号(+)表示一次或多次重复 ,方括号([])中的短语表示零次或一次出现 (换句话说,所包含的短语是可选的)。 *和+运算符尽可能紧密地绑定; 圆括号用于分组 。
所以,具体来说,以第一种形式:
try1_stmt ::= "try" ":" suite
("except" [expression [("as" | ",") identifier]] ":" suite)+
["else" ":" suite]
["finally" ":" suite]
else和finally子句是可选的([]) ,你只需要一个try语句和一个或多个(+) except子句。
在第二种形式中:
try2_stmt ::= "try" ":" suite
"finally" ":" suite
你只有一个try和一个finally子句,没有except子句。
请注意,对于第一种情况,else和finally子句的顺序是固定的。 finally子句后面的else子句导致SyntaxError 。
在一天结束的时候,这一切都归结为基本上不能有一个try子句, 只有一个else子句。 所以在代码形式中这两个是允许的:
try语句的第一种形式( 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")
第二种形式( try2_stmt ):
try:
x = 1/0
finally:
print("I'm mandatory in this form of try")
print("I always execute no matter what")
为了便于阅读PEP,请参阅PEP 341 ,其中包含两种形式的try语句的原始提案。
上一篇: Try statement syntax
