PEP 341 - 统一 try-except 和 try-finally
- 作者:
- Georg Brandl <georg at python.org>
- 状态:
- 最终
- 类型:
- 标准追踪
- 创建:
- 2005 年 5 月 4 日
- Python 版本:
- 2.5
- 后期历史:
摘要
此 PEP 提出更改 try 语句的语法和语义,以允许组合使用 try-except-finally 块。简而言之,这意味着以下代码将是有效的
try:
<do something>
except Exception:
<handle the error>
finally:
<cleanup>
理由/提案
try-except 语句和 try-finally 语句本身都有很多用例;然而,通常需要捕获异常并在之后执行一些清理代码。必须编写以下代码有点烦人,而且不够直观
f = None
try:
try:
f = open(filename)
text = f.read()
except IOError:
print 'An error occurred'
finally:
if f:
f.close()
因此,建议使用以下结构
try:
<suite 1>
except Ex1:
<suite 2>
<more except: clauses>
else:
<suite 3>
finally:
<suite 4>
与传统的
try:
try:
<suite 1>
except Ex1:
<suite 2>
<more except: clauses>
else:
<suite 3>
finally:
<suite 4>
完全相同。这与向后兼容,并且所有当前有效的 try 语句将继续正常工作。
语法更改
try 语句的语法,当前为
try_stmt: ('try' ':' suite (except_clause ':' suite)+
['else' ':' suite] | 'try' ':' suite 'finally' ':' suite)
将必须变为
try_stmt: 'try' ':' suite
(
(except_clause ':' suite)+
['else' ':' suite]
['finally' ':' suite]
|
'finally' ':' suite
)
实现
由于 PEP 作者目前不了解 CPython 实现,因此他无法提供一个。Thomas Lee 已提交了一个补丁 [2]。
然而,根据 Guido 的说法,实现它应该轻而易举 [1] - 至少对核心黑客来说。
该补丁已于 2005 年 12 月 17 日提交,SVN 修订版 41740 [3]。
参考
版权
本文件已置于公共领域。
来源: https://github.com/python/peps/blob/main/peps/pep-0341.rst
最后修改时间: 2023-09-09 17:39:29 GMT