What's the scope of using the 'finally' clause in python? [duplicate]

给你一囗甜甜゛ 提交于 2019-12-11 03:06:22

问题


Possible Duplicate:
Purpose of else and finally in exception handling

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?


回答1:


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')

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!"

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.




回答2:


The finally clause will always execute which is great if you missed an exception type in your code.

To quote the documentation:

If finally is present, it specifies a ‘cleanup’ handler. The try clause is executed, including any except and else clauses. If an exception occurs in any of the clauses and is not handled, the exception is temporarily saved. The finally clause is executed. If there is a saved exception, it is re-raised at the end of the finally clause. If the finally clause raises another exception or executes a return or break statement, the saved exception is lost. The exception information is not available to the program during execution of the finally clause.



来源:https://stackoverflow.com/questions/11722879/whats-the-scope-of-using-the-finally-clause-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!