Python 中的 try-finally 子句行为异常
try-finally clause in Python behaves unexpectedly
编辑:回想起来,这不是一个经过深思熟虑的问题,但我把它留在这里留给可能和我有同样误解的未来读者。
我对 try/except/finally 如何在 Python 中工作的理解可能有误,但我希望以下内容能够按照评论中的描述工作。
from sys import argv
try:
x = argv[1] # Set x to the first argument if one is passed
finally:
x = 'default' # If no argument is passed (throwing an exception above) set x to 'default'
print(x)
我希望上面的文件 (foo.py) 在 运行 时打印 default
作为 python .\foo.py
并且在 [=40] 时打印 bar
=] 作为 python .\foo.py bar
.
bar
功能按预期工作,但是,default
行为不起作用;如果我 运行 python .\foo.py
,我得到一个 IndexError:
Traceback (most recent call last):
File ".\foo.py", line 4, in <module>
x = argv[1]
IndexError: list index out of range
因此,我有两个问题:
- 这是错误还是 try-finally 块中的预期行为?
- 我是否应该在没有
except
子句的情况下永远不要使用 try-finally?
这是预期的行为。 try:..finally:...
单独 不会捕获异常 。只有 try:...except:...
的 except
子句可以。
try:...finally:...
只保证 finally
下的语句总是被执行,无论 try
部分发生什么,块是否成功或因为 [=16= 而退出]、continue
、return
或异常。所以 try:...finally:...
非常适合清理资源 ;无论块中发生什么,你都会得到 运行 代码(但请注意 with
statement and context managers let you encapsulate cleanup behaviour too). If you want to see examples, then the Python standard library has hundreds.
如果您需要在 try
块中处理 IndexError
异常,那么您 必须 使用 except
子句。您仍然可以使用 finally
子句 以及 ,它将在 except
套件具有 运行.
之后调用
如果您曾经使用过更旧的 Python 代码,您会在必须 运行 与 Python 2.4 或更旧 try:....finally:...
的代码中看到和 try:...except:...
从不一起使用。那是因为only as of Python 2.5两种形式统一了
编辑:回想起来,这不是一个经过深思熟虑的问题,但我把它留在这里留给可能和我有同样误解的未来读者。
我对 try/except/finally 如何在 Python 中工作的理解可能有误,但我希望以下内容能够按照评论中的描述工作。
from sys import argv
try:
x = argv[1] # Set x to the first argument if one is passed
finally:
x = 'default' # If no argument is passed (throwing an exception above) set x to 'default'
print(x)
我希望上面的文件 (foo.py) 在 运行 时打印 default
作为 python .\foo.py
并且在 [=40] 时打印 bar
=] 作为 python .\foo.py bar
.
bar
功能按预期工作,但是,default
行为不起作用;如果我 运行 python .\foo.py
,我得到一个 IndexError:
Traceback (most recent call last):
File ".\foo.py", line 4, in <module>
x = argv[1]
IndexError: list index out of range
因此,我有两个问题:
- 这是错误还是 try-finally 块中的预期行为?
- 我是否应该在没有
except
子句的情况下永远不要使用 try-finally?
这是预期的行为。 try:..finally:...
单独 不会捕获异常 。只有 try:...except:...
的 except
子句可以。
try:...finally:...
只保证 finally
下的语句总是被执行,无论 try
部分发生什么,块是否成功或因为 [=16= 而退出]、continue
、return
或异常。所以 try:...finally:...
非常适合清理资源 ;无论块中发生什么,你都会得到 运行 代码(但请注意 with
statement and context managers let you encapsulate cleanup behaviour too). If you want to see examples, then the Python standard library has hundreds.
如果您需要在 try
块中处理 IndexError
异常,那么您 必须 使用 except
子句。您仍然可以使用 finally
子句 以及 ,它将在 except
套件具有 运行.
如果您曾经使用过更旧的 Python 代码,您会在必须 运行 与 Python 2.4 或更旧 try:....finally:...
的代码中看到和 try:...except:...
从不一起使用。那是因为only as of Python 2.5两种形式统一了