Python - finally Termination Actions

Introduction

try statements can include finally blocks.

The finally specifies termination actions that always execute regardless of whether an exception occurs in the try block or not;

Demo

def fetcher(obj, index): 
    return obj[index] 
             # from   w  w  w.ja va2 s  .c  o  m
x = 'test' 
                  
try: 
     fetcher(x, 3) 
finally:                                # Termination actions 
     print('after fetch')

Result

Here, if the try block finishes without an exception, the finally block will run, and the program will resume after the entire try.

Demo

def fetcher(obj, index): 
    return obj[index] 
             #   ww  w . j  a v  a2 s .  c o m
x = 'test' 

def after(): 
    try: 
        fetcher(x, 4) 
    finally: 
        print('after fetch') 
    print('after try?') 

after()

Result