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
-
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.
-
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.
-
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!