- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Defining Clean Up Actions in Python
There are numerous situation occurs when we want our program to do this specific task, irrespective of whether it runs perfectly or thrown some error. Mostly to catch at any errors or exceptions, we use to try and except block.
The “try” statement provides very useful optional clause which is meant for defining ‘clean-up actions’ that must be executed under any circumstances. For example −
>>> try: raise SyntaxError finally: print("Learning Python!") Learning Python! Traceback (most recent call last): File "<pyshell#11>", line 2, in <module> raise SyntaxError File "<string>", line None SyntaxError: <no detail available>
The final clause will execute no matter what, however, the else clause executes only if an exception was not raised.
Example1 − Consider below example, where everything looks ok and writing to a file with no exception (the program is working), will output the following −
file = open('finally.txt', 'w') try: file.write("Testing1 2 3.") print("Writing to file.") except IOError: print("Could not write to file.") else: print("Write successful.") finally: file.close() print("File closed.")
On running above program, will get −
Writing to file. Write successful. File closed.
Example 2 − Let's try to raise an exception by making a file read-only and try to write onto it, thus causing it to raise an exception.
file = open('finally.txt', 'r') try: file.write("Testing1 2 3.") print("Writing to file.") except IOError: print("Could not write to file.") else: print("Write successful.") finally: file.close() print("File closed.")
Above program will give an output, something like −
Could not write to file. File closed.
In case we have an error, but we have not put any except clause to handle it. In such a case, the clean-up action (finally block) will be executed first and then the error is raised by the compiler. Let's understand the concept with the below example −
Example
file = open('finally.txt', 'r') try: file.write(4) print("Writing to file.") except IOError: print("Could not write to file.") else: print("Write successful.") finally: file.close() print("File closed.")
Output
File closed. Traceback (most recent call last): File "C:/Python/Python361/finally_try_except1.py", line 4, in <module> file.write(4) TypeError: write() argument must be str, not int
So from above, we can see that, finally, clause executes always, irrespective of whether an exception occurs or not.
- Related Articles
- How do I correctly clean up a Python object?
- How to clean up your online digital footprint?
- Defining a Function in Python
- How to scroll up/down a page using Actions class in Selenium?
- Defining Colors in CSS3
- Defining Keyframes in CSS3
- Defining Class Methods in Perl
- Defining static members in C++
- Defining new functions in Arduino
- PHP Defining namespace
- How are involuntary actions and reflex actions different from each other?
- Setting up Cookies in Python
- Sleep in JavaScript delay between actions?
- What are the Actions class in Selenium?
- What are JSP actions elements?
