尝试语句语法

fer*_*rry 7 python python-2.7

我一直在阅读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
Run Code Online (Sandbox Code Playgroud)

我最初认为这意味着try语句必须具有任何格式

  1. tryfinally
  2. try,except,elsefinally.

但在阅读文档后,它提到了这else是可选的,也是如此finally.所以,我想知道文档的目的是什么,向我们展示上面格式的代码?

Jim*_*ard 4

确实有两种形式的try声明。它们之间的主要区别是在子句的情况try1_stmtexcept必须指定

简介中| Python语言参考的记法,写法如下:

星号(*) 表示前一项重复零次或多次;同样,加号 (+) 表示一次或多次重复,方括号([ ]) 中的短语表示出现零次或一次(换句话说,括起来的短语是可选的)。* 和 + 运算符绑定尽可能紧密; 括号用于分组

因此,具体来说,在第一种形式中:

try1_stmt ::=  "try" ":" suite
               ("except" [expression [("as" | ",") identifier]] ":" suite)+
               ["else" ":" suite]
               ["finally" ":" suite]
Run Code Online (Sandbox Code Playgroud)

andelse子句是可选的,您只需要一个语句和finally一个或多个子句([])try(+) except

在第二种形式中:

try2_stmt ::=  "try" ":" suite
               "finally" ":" suite
Run Code Online (Sandbox Code Playgroud)

只有一个子句try和一个finally没有except子句的子句。


请注意,对于第一种情况,else 和finally 子句的顺序是固定的。子句后面的子句else会产生.finallySyntaxError

归根结底,这一切都归结为基本上无法同时拥有一个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")
Run Code Online (Sandbox Code Playgroud)

第二种形式(try2_stmt):

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

有关此主题的易于阅读的 PEP,请参阅PEP 341,其中包含两种形式的声明的原始提案try