/    /  Python Clean-up Actions

Clean-Up Actions

When we are writing any code, sometimes we want to execute some action at any cost irrelevant to the errors produced. In Python, we can perform this action by using finally statement in try and except statements. If there is any action in Finally clause, it will get executed even though there is an exception in the try and except statements. But if an exception occurs and cannot be handled by except clause, then finally clause occurs first and then the error is raised as default during the execution. This entire process is called as Clean Up Actions.

Python Code:

while True:
    try:
        x=int(input('Enter the number : '))
        break
    except ValueError:
        print("Not a Valid Number")
    finally:
        print("This is a finally clause..!")

Python Code:

def minus(x, y): 
    try: 
# subtracting two numbers x and y 
        result = x - y 
        if x < y:
            raise ValueError
    except ValueError: 
        print("Sorry ! X must be greater than y ") 
    else: 
        print("Your answer is :", result) 
    finally: 
        print("finally clause is raised ") 
  
#providing parameters to the program
minus(3, 4) 
minus(5, 2)

As discussed above, if an error occurs during the execution of the program which cannot be handled by except statement, then the finally statement is first displayed and the error is displayed after the finally clause as the output.

Python Code:

def minus(x, y): 
    try: 
# subtracting two numbers x and y 
        result = x - y 
        if x < y:
            raise ValueError
    except ValueError: 
        print("Sorry ! X must be greater than y ") 
    else: 
        print("Your answer is :", result) 
    finally: 
        print("finally clause is raised ") 
  
#providing invalid parameters to the program
minus(1, '0')

Output:

finally clause is raised

—————————————————————————

TypeError                                 Traceback (most recent call last)

<ipython-input-16-e0befcdd216f> in <module>

     13

     14 #providing invalid parameters to the program

—> 15 minus(1, ‘0’)

<ipython-input-16-e0befcdd216f> in minus(x, y)

      2     try:

      3 # subtracting two numbers x and y

—-> 4         result = x – y

      5         if x < y:

      6             raise ValueError

TypeError: unsupported operand type(s) for -: ‘int’ and ‘str’