Defining Cleanup Actions in Python



Think of the task that you always want your program to do, whether it works fine or throws any errors. For example, we use the try operator with the optional —  “finally” to perform cleanup actions that must be performed under all conditions. 
Cleanup Actions: before exiting the try statement, a finally clause is always executed, regardless of whether any exception has been thrown or not. These are points for defining the cleaning actions to be carried out under all circumstances. 
Whenever an exception is thrown and it is not handled by the exception clause, finally occurs first, and then the default error [Code 3] occurs.

Python programs illustrating “Determine Cleanup Actions”

Code 1: Code runs fine and action is taken at the end by clearing

# Python code for illustration
# clear actions

def divide (x, y):

try :

  # Gender department: gives only fractional part as an answer

  result = x / / y

except ZeroDivisionError:

print ( "Sorry! You are dividing by zero " )

  else :

print ( "Yeah! Your answer is:" , result)

finally :

print ( "I`m finally clause, always raised !!" )

 
# Look at the parameters and notice how the program works

divide ( 3 , 2 )

Output:

 Yeah! Your answer is: 1 I`m finally clause, always raised !! 

Code 2: The error is in the code and is carefully handled in a exception . Note that the cleanup action is performed at the end.

# Python code for illustration
# clear actions

def divide (x, y):

try :

# Gender department: gives only fractional part as answer

  result = x / / y

  except ZeroDivisionError:

  print ( " Sorry! You are dividing by zero " )

  else :

print ( "Yeah! Your answer is:" , result)

finally :

print ( "I`m finally clause, always raised !!" )

 
# Look at the parameters and notice how the program works

divide ( 3 , 0 )

Output:

 Sorry! You are dividing by zero I`m finally clause, always raised !! 

Code 3: Code, raise a bug, but we have nothing except a caveat to handle it. So the cleanup is done first, and then the compiler throws an error (default) .

# Python code for illustration
# clear actions

def divide (x , y):

try :

# Gender department: gives only fractional part as an answer

result = x / / y

except ZeroDivisionError: 

print ( "Sorry! You are dividing by zero " )

  else :

print ( "Yeah! Your answer is:" , result)

finally :

print ( "I`m finally clause, always raised !!" )

 
# Look at the parameters and notice how the program works

divide ( 3 , "3" )

Exit:

 I`m finally clause, always raised !! 

Error :

 Traceback (most recent call last): File "C: /Users/DELL/Desktop/Code.py", line 15, in divide (3, "3") File "C: /Users/DELL/Desktop/Code.py", line 7, in divide result = x // y TypeError: unsupported operand type (s) for //: `int `and` str` 

This article is courtesy of Mohit Gupta_OMG