try/except/finally

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.

Note that the as variable assigns the raised exception to the e variable, but it will be deleted once we're out of the except clause.

try/except statements allow us to dodge an exception if something goes south. This is a great solution in terms of adding some fault tolerance to the code. The danger with this approach is being overly fault tolerant, meaning that the code will keep working OK in a situation where you'd ideally want to intervene and halt it. Let's now talk about our last statement for today—the with statement.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset