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   www  .ja v a  2  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] 
             #  w  w  w  .j a  va  2 s. c om
x = 'test' 

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

after()

Result