Book Image

Python Essentials

By : Steven F. Lott
Book Image

Python Essentials

By: Steven F. Lott

Overview of this book

Table of Contents (22 chapters)
Python Essentials
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Using a finally clause


We can include a finally clause on a try statement. This contains a suite of statements that will always be executed at the end of the try statement. This means that the happy path, as well as the exception paths, will always execute the finally suite. Here's a summary of how this looks:

try:
    # Something that might fail.
except SomeException:
    # Fallback plan to handle failure.
finally:
    # Always executed.

We use this when we have cleanup or a concluding suite of statements that must always be executed. One of the most common use cases for this is to close a file or a network connection even if an exception was raised and handled properly.

In many cases, we can use a context manager to properly close a file or network connection. We can use contextlib.closing() to wrap objects which have a close() method but are not proper context managers. We'll look at context managers in Chapter 10, Files, Databases, Networks, and Contexts.