Python Exception Handling With Finally


In the previous article, you learned about different ways of handling an exception in the try block. However, there are some codes that are bound to run no matter what.

It does not matter if an exception happens or not.A block of code must run regardless of the outcome. These type of codes run in finally block.

Motivation for Finally Keyword

What is the reason to use finally as part of exception handling code. It is because the exception handling process starts at try block and we want to target try block for which there must be exception handling.However, if you notice all codes need not be part of try block.

In this process of simplification, some codes are clearly not part this try-catch scenario.Therefore, these codes that are independent of try-catch are put at the end of the exception handling process. Hence, the name finally.

Example Program: Python Finally

In this example, we will use the file handling code by python. The python program opens a file called myFile.txt and then read its content. If the file does not exist, or there is no permission to open the file we will catch it using except block.


At the end of the program the opened file must be closed no matter what. This is something we need to do regardless of try-catch block. Therefore, we can include this code in finally.

# Program to demo finally block in Python exception handling
    f = open("myFile.txt", "r")
except Exception as err:
    result =

The program opens the file and read the content of the file. At the end, it must close the open file regardless of whether file was opened or failed to open.


The above is the code to close the file.

In the next article, we will discuss about nesting of try-except blocks.


Python Programming: Using Problem Solving Approach

Python Programming is designed as a textbook to fulfil the requirements of the first-level course in Python programming. It is suited for undergraduate degree students of computer science engineering, information technology as well as computer applications. This book will enable students to apply the Python programming concepts in solving real-world problems. The book begins with an introduction to computers, problem solving approaches, programming languages, object oriented programming and Python programming. Separate chapters dealing with the important constructs of Python language such as control statements, functions, strings, files, data structures, classes and objects, inheritance, operator overloading and exceptions are provided in the book. Each chapter ends with objective-type questions, review questions, programming and debugging exercises to facilitate revision and practice of concepts learnt.