# Defining Clean Up Actions in Python

PythonServer Side ProgrammingProgramming

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.

Published on 19-Feb-2019 12:19:37