Define Clean up actions in Python

Clean up actions are those statements within a program that are always executed. These statements are executed even if there is an error in the program. If we have used exception handling in our program then also these statements get executed. So, basically we can say that if we a particular part to run always, we use clean up actions.

In Python, we use finally keyword to state the part of the code that is going to execute every time the program runs. That is every code line under finally is clean up action.

There can be three different cases in code. These three types can be defined as follows:

  1. Code runs normally: In this case, there is no problem with the working of our code. Neither there is an error. Hence, in this case, the clean up action is taken up at the end.
  2. Code raises an error that is handled in the except clause: In this case, the compiler prints the statements under the finally clause at the very end of the code just like the previous case.
  3. Error without any except clause: In this case, the compiler first prints the statements under the finally clause. After printing the finally clause, the compiler prompts an error with a description of it.

Given is a very simple example describing all the three cases discussed above. In this example code, a user-defined function for dividing two numbers is used to show all the three cases. This code handles the ZeroDivisionError using the except clause. We call this function 3 different with different arguments corresponding to three different cases which are discussed above. Hence, the code is:

Python Code: Define Clean up actions

#Python 3 code to show how clean actions work

#Function for dividing
def div(a,b):

#Activates only when we are trying to divide by 0
    except ZeroDivisionError:
        print("Can't divide by zero")
#Runs everytime except when we are dividing by zero
        print("Answer is ",q)

#Runs everytime irrespective of the number we are choosing to divide by
        print("I will always be printed")

#Case 1: When b is not equal to 0

#Case 2: When b is equal to zero

#Case 3: When b is a string


Answer is  5
I will always be printed

Can't divide by zero
I will always be printed

I will always be printed
Traceback (most recent call last):
  File "E:/snu/Codespeedy/Programs for articles/", line 27, in <module>
  File "E:/snu/Codespeedy/Programs for articles/", line 6, in div
TypeError: unsupported operand type(s) for //: 'int' and 'str'

Leave a Reply

Your email address will not be published. Required fields are marked *