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
try:
    f = open("myFile.txt", "r")

except Exception as err:
    print(err)
else:
    result = f.read()
    print(result)
finally:
    f.close

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.

f.close 

The above is the code to close the file.

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

Please support us by disabling your adblocker or whitelist this site from your adblocker. Thanks!

turn of adblocker imag