Форум сайта python.su
0
Обясните тугодуму. Зачем в исключениях finally. Судя по описанию блок исполняется после try или except - то есть в любом случае он будет выполнен. Но я не могу понять зачем оно нужно если код под except все равно дальше вниз будет исполнятся. Другими словами какая разница в:
try: someCommands1 except: someCommands2 finally: endCommands
try: someCommands1 except: someCommands2 endCommands
Офлайн
32
finally как бы гарантирует выполнение, полезный пример сейчас не вспомню, но пример отличия вот:
def foo(): try: return finally: print 'moo'
Офлайн
568
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>
Офлайн
88
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
Офлайн
0
Shaman
clause
Офлайн