August 2019
Beginner
482 pages
12h 56m
English
The try statement supports yet another option – the finally clause. When added, finally represents the code that will be executed, irrespective of which branch of try/except actually did run in the end. It is usually used to release external resources—a close connection to the file or the database. Consider this example. Here, we're attempting to open the file and perform certain computations:
try: file = open("test.txt") # some operations on file finally: file.close()
No matter what happens within try, the file will be properly closed. This on the way out principle will work with other events as well, including break, continue, and return.