Найти - Пользователи
Полная версия: Зачем нужен finally
Начало » Python для новичков » Зачем нужен finally
1
alexeyvanzhula
Обясните тугодуму. Зачем в исключениях finally. Судя по описанию блок исполняется после try или except - то есть в любом случае он будет выполнен. Но я не могу понять зачем оно нужно если код под except все равно дальше вниз будет исполнятся. Другими словами какая разница в:
try:
    someCommands1
except:
    someCommands2
finally:
    endCommands
и
try:
    someCommands1
except:
    someCommands2
endCommands
o7412369815963
finally как бы гарантирует выполнение, полезный пример сейчас не вспомню, но пример отличия вот:
def foo():
    try:
        return
    finally:
        print 'moo'
FishHook
try:
    f=open('uu.txt')
    a = int("k")
except:
    print "K is not int"
finally:
    print f 
    f.close()
 print f  

<open file 'uu.txt', mode 'r' at 0x00000000024BE390>
<closed file 'uu.txt', mode 'r' at 0x00000000024BE390>
Shaman
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.

try:
    1 / 0
except:
    print 1
    raise Exception('!!!')
finally:
    print 2
Выдаёт:
1
2

Traceback (most recent call last):
File “<pyshell#14>”, line 5, in <module>
raise Exception('!!!')
Exception: !!!
alexeyvanzhula
Shaman
clause

Этого ответа и ожидал. Теперь все встало на свои места. Спасибо всем!
This is a "lo-fi" version of our main content. To view the full version with more information, formatting and images, please click here.
Powered by DjangoBB