Finally Keyword In Python

Introduction:

  • The keyword finally in Python marks the cleanup handler associated with a try block.
  • The finally block is an optional block. It is executed after the execution of the associated except and else handlers.

Why cleanup of resources is required:

  • While an exception can occur for several reasons in a Python program, it is important to free up the associated resources if any, after an exception.
  • Doing so helps in avoiding resource leakages, which will affect the performance of a Python program negatively.
  • Also some of the resources may be corrupt while continuing the program execution after an exception has been handled.

For these reasons the provision of having a finally handler is provided. Inside the finally handler the cleanup code can be placed.For example, a file handle or a socket connection to a remote host would have been opened but not closed after an exception has occurred. Freeing of such resources by calling the relevant close() methods can be done inside the finally block.

 

Example:

In the Python example below the file open mode is by mistake given as “wb” which triggers an exception after the file has been opened and a write operation is invoked. In a complex software system such circumstances can arise often owing to various reasons. To prevent resource leakages during such scenarios it is always better to have a finally clause to cleanup things like open files, open network connections and so on.

fileNamePrefix  = "Group";

fileExtension   = ".csv";

recfileCount    = 4;

pathPrefix      = "/files/";

fileMode        = "wb";

 

for i in range(0, recfileCount-1):

    fileName = "%s%s%d%s"%(pathPrefix,fileNamePrefix, i, fileExtension);

    print(fileName);

    try:

        file = open(fileName, fileMode);

        file.write("Init");

    except Exception as ex:

        print(ex);

    finally:

        print("Freeing up allocated resources...");

        file.close();

 

Output:

/files/Group0.csv

a bytes-like object is required, not 'str'

Freeing up allocated resources...

/files/Group1.csv

a bytes-like object is required, not 'str'

Freeing up allocated resources...

/files/Group2.csv

a bytes-like object is required, not 'str'

Freeing up allocated resources...


Copyright 2020 © pythontic.com