我一直在读python documentation ,有人可以帮我解释一下吗?
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 语句必须具有任一格式
try
和finally
或者try
、except
、else
ANDfinally
。
但是看了文档后,提到else
是可选的,finally
也是可选的。所以,我想知道文档以上述格式开始向我们展示代码的目的是什么?
最佳答案
您确实有两种形式的try
语句。它们之间的主要区别在于,在 try1_stmt
的情况下,必须指定一个 except
子句。
在 Introduction | Notation 的Python Language reference,是这样写的:
A star (*) means zero or more repetitions of the preceding item; likewise, a plus (+) means one or more repetitions, and a phrase enclosed in square brackets ([ ]) means zero or one occurrences (in other words, the enclosed phrase is optional) . The * and + operators bind as tightly as possible; parentheses are used for grouping.
所以,具体来说,在第一种形式中:
try1_stmt ::= "try" ":" suite
("except" [expression [("as" | ",") identifier]] ":" suite)+
["else" ":" suite]
["finally" ":" suite]
else
和finally
子句是可选的([])
,你只需要一个 try
语句和一个 或多个(+)
except
子句.
第二种形式:
try2_stmt ::= "try" ":" suite
"finally" ":" suite
您只有有一个try
和一个没有except
子句的finally
子句。
请注意,对于第一种情况,else 和 finally 子句的顺序是固定的。 else
子句后跟 finally
子句会导致SyntaxError
。
归根结底,这一切都归结为基本上无法将 try
子句与 only 和 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
语句的原始建议。
关于python - Try语句语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34101625/