Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Clean-up actions
3.
Python Programs to illustrate clean-up actions
3.1.
Case 1
3.1.1.
Example
3.2.
Case 2
3.2.1.
Example
3.3.
Case 3
3.3.1.
Example
4.
FAQs
5.
Conclusion
Last Updated: Mar 27, 2024
Easy

Clean-up Action In Python

Author Sanjana Yadav
0 upvote
Master Python: Predicting weather forecasts
Speaker
Ashwin Goyal
Product Manager @

Introduction

There are a variety of situations in which we want our program to perform a given task, regardless of whether it runs correctly or throws an error. We use the try and except block to catch any errors or exceptions.

The "try" statement includes a handy optional clause "finally" for describing "clean-up actions" that must be performed regardless of the conditions.

Must Recommended Topic, Floor Division in Python

Clean-up actions

Whether or not an exception is thrown, the "finally" phrase is always executed before exiting the try statement. These clauses outline the clean-up procedures that must be followed in all situations.

When an exception arises that isn't handled by the except clause, the finally occurs first, and then an error is raised as default.

Also read, Fibonacci Series in Python and Convert String to List Python.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Python Programs to illustrate clean-up actions

Case 1

The code runs normally, and clean-up is done at the end.

Example

def division(a, b):
    try:
        res = a // b
    except ZeroDivisionError:
        print("Division by Zero is not allowed! ")
    else:
        print("The answer is:", res)
    finally:
        print("This is finally clause, always raised!")

division(4, 2)

Output

The answer is: 2
This is finally clause, always raised!

Case 2

The except clause correctly handles code that causes an error. It's important to note that clean-up action is taken in the end.

Example

def division(a, b):
    try:
        res = a // b
    except ZeroDivisionError:
        print("Division by Zero is not allowed!")
    else:
        print("The answer is:", res)
    finally:
        print("This is finally clause, always raised!")

division(4, 0)

Output

Division by Zero is not allowed!
This is finally clause, always raised!

Case 3

We have no except clause to handle the error that is raised by the code. As a result, clean-up is done first, and then the compiler raises an error (by default).

Must Read, leap year program in python

Example

def division(a, b):
    try:
        res = a // b
    except ZeroDivisionError:
        print("Division by Zero is not allowed!")
    else:
        print("The answer is:", res)
    finally:
        print("This is finally clause, always raised!")

division(4, "4")

Output

This is finally clause, always raised!
Traceback (most recent call last):
  File "e:\file1.py", line 12, in <module>
    division(4, "4")
  File "e:\file1.py", line 3, in division
    res = a // b
TypeError: unsupported operand type(s) for //: 'int' and 'str'

 

You can try it on online python compiler.

Check out Escape Sequence in Python

Read More, python packages

FAQs

  1. What is clean-up action?
    Clean-up actions are statements that are always executed in a program. Even if the program contains an error, these statements are performed. These statements are also performed if we have implemented exception handling in our program.
     
  2. What is the difference between error and exception in Python?
    Errors are issues in a program that causes the program to halt its execution. On the other hand, exceptions are raised when internal events occur that disrupt the program's usual flow.
     
  3. What is try and except in Python?
    The try block allows you to check for errors in a block of code. You may handle the error with the except block. When there is no error, the else block allows you to run code.

Conclusion

In this article, we have extensively discussed the clean-up action in Python. We saw different cases to perform clean-up actions using several examples.

We hope that this blog has helped you enhance your knowledge of the clean-up action in python and if you would like to learn more about exception handling in python, check out our articles on exception handling in python. Do upvote our blog to help other ninjas grow. Happy Coding!

Previous article
Built-in Exception in Python
Next article
NZEC Error in Python
Live masterclass