Python finally keyword explained with examples

The finally keyword is used alongside try-except blocks when handling exceptions. Although it is an optional block, it can be very handy in certain situations.

For example, there will be scenarios where we’ll need to close a file or a network connection before the program is terminated. The finally keyword is utilized here because, regardless of whether an error pops up or not, it will always be executed.

The finally block is executed after the try and except blocks are executed first. Also, you can just execute the finally block after the try block without using the except block.

Example#1

Here’s an example to help you understand

try:
    print(1/0)
except ZeroDivisionError:
    print("Error: You cannot divide by 0. Please try again.")
finally:
    print("This is always executed!")
Error: You cannot divide by 0. Please try again.
This is always executed!

Here, all three try, except, and finally block are executed.

Here’s the same example but we don’t trigger any error:

try:
    print(1/2)
except ZeroDivisionError:
    print("Error: You cannot divide by 0. Please try again.")
finally:
    print("This is always executed!")
0.5
This is always executed!

In this case, only the try and finally block have been executed.

This is because, as mentioned earlier, the finally block is always executed in any situation!

The following flowchart visualizes the same process neatly:

Example#2

Let us see one more example where we perform some cleanup actions in the finally block.

Consider the situation where the program may be closed due to an error before we have closed an open file.

The finally block can be used in this situation to release the resources as shown below.

try:
    file = open("example.txt", "r")
    #perfoming file operations
    
    #raising an error
    print(10/0) 
except ZeroDivisionError:
    print("Error: You cannot divide by 0. Please try again.")
finally:
    #closing the file 
    file.close() 

In this way, the finally block ensures the file is closed regardless of whether an exception was raised or not to release memory resources!

There is one more keyword that can be used in the exception context: else. You can read how else fits in with try, except and finally in the following article.

Python: “try-except-else-finally” Usage Explained!

Now that you can write try-except statements like a pro, next I invite you to learn how to debug exceptions the professional way!

And with that, I will end this article.

Congratulations on making it to the end of the article, not many have the perseverance to do so!

I hope you enjoyed reading this article and found it useful!

Feel free to share it with your friends and colleagues!

If your thirst for knowledge has not been quenched yet, here are some related articles that might spark your interest!

Related Articles

Python: “try-except-else” Usage Explained!

Python: “try-except-finally” Usage Explained!

Python catch multiple exceptions

Thanks to Namazi Jamal for his contributions in writing this article!

Photo of author
Editor
Balaji Gunasekaran
Balaji Gunasekaran is a Senior Software Engineer with a Master of Science degree in Mechatronics and a bachelor’s degree in Electrical and Electronics Engineering. He loves to write about tech and has written more than 300 articles. He has also published the book “Cracking the Embedded Software Engineering Interview”. You can follow him on LinkedIn