在python中使用'finally'子句的范围是什么? [英] What's the scope of using the 'finally' clause in python?
问题描述
可能重复:
其他目的,最后是异常处理
Possible Duplicate:
Purpose of else and finally in exception handling
我想了解为什么try/except
语句中存在finally
子句.我了解它的作用,但很明显,如果它在语言中应占一席之地,我会丢失一些东西.具体来说,在finally
字段中写子句与在try/except
语句之外写子句有什么区别?
I'd like to understand why the finally
clause exists in the try/except
statement. I understand what it does, but clearly I'm missing something if it deserves a place in the language. Concretely, what's the difference between writing a clause in the finally
field with respect of writing it outside the try/except
statement?
推荐答案
try
套件可以得到执行,无论try
套件中发生了什么.
The finally
suite is guaranteed to be executed, whatever happens in the try
suite.
使用它来清理文件,数据库连接等:
Use it to clean up files, database connections, etc:
try:
file = open('frobnaz.txt', 'w')
raise ValueError
finally:
file.close()
os.path.remove('frobnaz.txt')
这是真的,无论异常处理程序(except
套件)是否捕获到异常,或者您的代码中是否有return
语句:
This is true regardless of whether an exception handler (except
suite) catches the exception or not, or if there is a return
statement in your code:
def foobar():
try:
return
finally:
print "finally is executed before we return!"
在循环中使用try
/finally
语句,然后使用continue
或break
中断循环,将再次执行finally
套件.保证在所有情况下都可以执行.
Using a try
/finally
statement in a loop, then breaking out of the loop with either continue
or break
would, again, execute the finally
suite. It is guaranteed to be executed in all cases.
这篇关于在python中使用'finally'子句的范围是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!