Python Finally Keyword
Python provides a keyword finally that can be optionally used with the try statement. The code within the block of the finally keyword is always executed no matter what.
The finally keyword is usually used to free resources, such as closing database connections, closing files after reading, etc, regardless of whether an exception occurs.
file_not_found = False try: file = "test.txt" with open(file) as tf: lines = tf.readlines() for line in lines: print(line) except FileNotFoundError as ex: print("Error reading file : " + str(ex)) file_not_found = True finally: if not file_not_found: print("Closing file...") tf.close()