python - Try语句语法

标签 python python-2.7

我一直在读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 语句必须具有任一格式

  1. tryfinally 或者
  2. tryexceptelse AND finally

但是看了文档后,提到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]

elsefinally 子句是可选的([]),你只需要一个 try 语句和一个 或多个(+) except 子句.

第二种形式:

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

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


请注意,对于第一种情况,else 和 finally 子句的顺序是固定的。 else 子句后跟 finally 子句会导致SyntaxError

归根结底,这一切都归结为基本上无法将 try 子句与 onlyelse 一起使用条款。所以在代码形式中,这两个是允许的:

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/

相关文章:

python - 如何获得一系列列表的基本统计数据?

python - 如何比较列表与列表的不均匀列表

python - 尝试使用 pip3 安装 virtualenvwrapper

python - Django 中的可重用模态成员

python - 在 debian 中守护 python 脚本

python - 使用 python 在 selenium 中打开多个选项卡

python - 如何创建一个返回从 n 到 1 的整数列表的函数?

windows - 多处理池方法挂起但处理方法工作

Python2.5到Python2.7性能下降

python - 不在python中写入文件