Python  Finally Block

Python Finally Block

posted 9 min read

Sometimes, when you are working in your program, a situation comes where file handling is used for performing operations on the file. However, after completing the operation, you must close the file. Also, when you use the database connection in your program, the connection needs to be closed after the task completion. Wondering how you can achieve it by using exception handling? It is quite easy because you simply put that code in the finally block after the try and except block during your program development. In this article, I will cover the detailed overview of the finally block, when it is needed, its purpose, and some examples with the help of code. Let's get started.

Finally Block in Python: An Overview

In Python, the finally block is another key concept of exception handling after try and except block. This expression is used as code cleaning action or logic cleaning in programming, which means when you use the resource of a computer, you have to return it after achieving the result. Additionally, the finally block is utilized for resource management. While working with try and except block, you put the piece of code in the finally block that needs to be executed regardless of an exception occurrence.

Finally Block: Definition

The finally block in exception handling is the block used in conjunction with the try-except block. It defines the piece-of-code that needs to be executed at the end, whether the exception occurs or not. The code written inside this block is used as a cleaning operation. It also ensures that whether the exception is encountered in the try block or handled in the except block, the finally block will always execute the code inside it.

Syntax for Finally Block

   
try:   
#code that needs to be tested and can cause an exception   
pass   

except exception1:   
#code to handle the exception1   
pass 
   
finally: 
#code that needs to run whether exceptions occur or not 
pass 
  

Purpose of Finally Block

The finally block has a very crucial role in programming language. It is not just a simple block that will execute whether errors occur or not, but it will manage the code and make the program robust. The purpose of the finally block in exception handling is:

  • It is used for cleanup activities when you are working in the program using the file. At the end, you can put the close file code in the finally block that ensures the resource is released without creating any problems. Also, it ensures resource management like network connection and database connection closing that resolves the issue of resource leak and deadlock conditions.
  • The code that is compulsory to run regardless of exception occurrence or not will also be achieved by using the finally block. It guarantees the execution of specific code that is required to run before the execution of other methods in the program like login function or age checking before vote casting function.
Tip: Try to use the exit code in the finally block that doesn't need to be tested before execution.

How Execution Flow in Try-Except-Finally Blocks?

As illustrated in the flow diagram, suppose you write a simple Python program in which you are opening a database connection. During coding, you start from the try block to handle if the error occurs beforehand. Now, if the compiler executes the program and gets an error instead. The compiler stops the execution, tries to resolve the exception first, and jumps to the except block. If there is no error in the try block, the else block will print the result. It ensures no error in the try block code because this block will only run when no exception is present. After that, the Finally is the code block which will always get executed irrespective of whether you had an exception in your code or not. If you have opened a database connection it is essential to close those connections and the code for closing the connection is written generally in the finally block regardless of exception otherwise you will run out of your connection pool.

Note: The else block code depends on the try block code where the finally block code is the concluding code.

Else Block Vs Finally Block

Now, you are thinking about why you use the else block when you are using the finally block, both blocks are part of exception handling and are used after the try-except block, but each has its use case.

  • The Except block helps us by ensuring that the piece of code inside the block will execute only when there is no exception error in the program. If the exception is encountered in the try block, which is handled by the except block, then the compiler stops the executions there. But if the try block runs successfully without error, then else block will execute.
  • The Finally block helps us by ensuring that the piece of code inside the block will execute in any case, regardless of the exception encountered in the program. It helps us to manage resources that are used during the program execution, i.e. closing database connections and files that would cause resource wastage and deadlock conditions. It is like using it for concluding a task at the end.
Caution: Remember, the code you put in else and finally block should be clean and does not cause any error. Otherwise, the exception is not caught in these block

Code Demonstration: Finally Block

There are many ways of using the finally block for exception handling implementation in your Python program.

Finally Block Code: Without Exception Handling

print("SIMPLE CALCULATOR")  
print("Having operation '*' and '/'")  
def multiplication(num1, num2): #function for multiplication  
    return num1 * num2  
def division(num1, num2): #function for division  
    try:  
        num3 = num1 / num2 #this line will give exception if num2 values is zero  
        return num3  
    except ZeroDivisionError: #if this exception occurs, then the compiler jumps to this part   
        print("Error: you try to divide the number with 0")   
        return None  
    finally: 
        print("This is the end of Division Function") #run always when the code executes 
result = multiplication(8, 0)  
result1 = division(8, 8)  
print("Multiplication of two numbers:" , result)  
print("Division of two numbers:" , result1) 

In the above code, I create two functions, i.e. for multiplication and division operations. Now in division operation when the user enters the value of the denominator. It will print the result of the calculation also the print line in the finally block is also displayed on the terminal. It's because whether an exception occurs or handles, it will print the line. Now you can test it by giving different values of denominators.

Output

Finally Block Code: With Exception Handling

print("SIMPLE CALCULATOR")  
print("Having operation '*' and '/'")  
def multiplication(num1, num2): #function for multiplication  
    return num1 * num2  
def division(num1, num2): #function for division  
    try:  
        num3 = num1 / num2 #this line will give exception if num2 values is zero  
        return num3  
    except ZeroDivisionError as e: #if this exception occurs then the compiler jumps to this part   
        print("Error: you try to divide the number with 0") 
        print(type(e)) #prints the exception class name  
        return None  
    finally: 
        print("This is the end of Division Function") #run always when the code executes 
result = multiplication(8, 5)  
result1 = division(8, 0)  
print("Multiplication of two numbers:" , result)  
print("Division of two numbers:" , result1)  

In this code snippet, you can see that the exception occurs in the code as I am passing the value of the denominator as 0. This raises the exception zero division error exception. But if you look carefully at the output image, the finally block is still printing the line. Regardless of the code with and without exception handling, this piece of code still displays the print statement.

Output

Finally Block Code: With Else Block

def read_file(file_path): 
    try: 
        with open(file_path, 'r') as file: 
            content =  file.readlines() 
    except FileNotFoundError as e: 
        print("Error: The file does not exist.") 
        print(type(e)) 
        return None 
    else: 
        print("There is no exception occur in the program") 
        return content 
    finally: 
        print("Finished processing the file.") 
        file.close() 
file_path = "Content.txt" 
content = read_file(file_path) 
print("The Content of file is", content) 

In the above code as there is no exception encountered the else block will also run with the finally block. It will only run when there is no exception in the program, but it does not affect the execution of the finally block because whether the exception occurs or not the finally block will always run the code inside it.

Output

FAQs Q: Can I use try and finally block without except block?
A: Yes, you can because the except block is used for handling the exception and to catch the error in the try block so if you don't want to handle the error it does not affect the code of the finally block.
Q: Can I have more than one finally block in the program?
A: Yes, if you want to use multiple finally blocks you can use it but make sure that each block code is clean and has a minimum chance of error.

Wrapping Up

In this article, we talked about the "Exception handling; Using Finally block" in Python. We saw examples with the help of coding that explain the purpose of the finally block other than a try-except block and see the difference in the finally and else blocks. Ultimately, you understand that the finally block has an important role in exception handling as it is used for the implementation of concluding and finalizing code part in the program. It will benefit you with code cleanup operations and resource management as well. Also, it runs the code in all circumstances to make it a robust and efficient application. If you understand the use of the finally block you will not only make your application error-prone but also manage the resources used in the program. Hope this guide is helpful for you. Happy Coding!

Reference

Finally Block in python

If you read this far, tweet to the author to show them you care. Tweet a Thanks

More Posts

Python Opening & Reading Files

Abdul Daim - Mar 8

Python Try Except Blocks

Abdul Daim - Mar 4

Setting up Virtual Environment in Python

Tejas Vaij - Apr 20

Mastering Data Visualization with Matplotlib in Python

Muzzamil Abbas - Apr 18

Opening & Reading Files Handling in Python

Abdul Daim - Apr 12
chevron_left