Python's Finally block In Try Except (Python 3 )

Python's Finally block In Try Except

The finally block is executed regardless of whether an exception occurs or not. Finally blocks are useful, for example, when you want to close a file or a network connection regardless of what happens. After all, you want to clean up resources to prevent memory leaks.

In this example we open a file without using the with statement, forcing us to close it ourselves. The finally block is ideal for this situation.

Now change the writing mode to 'r' instead of 'w'. You'll get an error since the file does not exist. Despite this exception, we try to close the file anyway thanks to the finally block. This in turn goes wrong too: a NameError exception is thrown because the file was never opened, and hence f does not exist. You can fix this with a nested try.. except NameError. Try it for yourself.

This example is from my Python Tutorial on Python Exceptions.

Edit and run this Python 3 example code

This code is editable and runnable. You can run "Python's Finally block In Try Except" by pressing the run button. It will be executed in our backend and the result (stdout and stderr) is displayed in addition tabs.

Share "Python's Finally block In Try Except"

Share this crumb (Python's Finally block In Try Except) with your friends and colleagues to help them learn more about Python 3 programming.

Twitter, Facebook, LinkedIn

On Twitter, Facebook, and LinkedIn, simply paste the URL in your post and watch the magic unfold.


If you want to embed the crumb in an iframe, use the following code:

oEmbed (WordPress)

We support oEmbed, but most sites use allowlisting. On WordPress, oEmbed is supported out of the box, but see the note below.

If you plan to use heavily on Wordpress, you can use the following PHP code to allowlist our site and unlock all the functionalities of our crumbs:
wp_oembed_add_provider( '*', '' ); is a service that allows you to embed content from other sites. We will request to be added to the list of trusted sites once we're out of beta.