在python中使用'finally'子句的范围是什么? [英] What's the scope of using the 'finally' clause in python?

查看:157
本文介绍了在python中使用'finally'子句的范围是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
其他目的,最后是异常处理

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语句,然后使用continuebreak中断循环,将再次执行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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆