- Python Snacks
- Posts
- Understanding Python's finally statement
Understanding Python's finally statement
This is a control flow tool you should've learned yesterday.
Python’s finally statement is a control flow tool that should be added to your toolbelt.
This statement is normally combined with a try/except block to execute code regardless if an exception is thrown or not.
Using finally in a try/except block
Normally, your try/except statements may look something like this:
try:
file = open('example.txt', 'r')
data = file.readlines()
except FileNotFoundError:
print("File not found!")
In the snippet above, if the file doesn’t exist we’ll throw an error. However, we may want to do some additional steps.
When we combine the above snippet with a finally statement, we can perform additional steps, such as closing the file:
try:
file = open('example.txt', 'r')
data = file.readlines()
except FileNotFoundError:
print("File not found!")
finally:
file.close()
print('File has been closed.')
When a finally statement is paired with a try/except statement, the finally statement will always execute whether an exception is thrown or not.
Similarly, we don’t need an except statement (but it’s good practice to have this for logging/debugging purposes):
try:
file = open('example.txt', 'r')
data = file.readlines()
finally:
file.close()
print('File has been closed.')
Use cases for the finally statement
There are many reasons why you may want to leverage this. Various real-world applications may include:
Resource Cleanup (e.g., File Handling): Ensuring that resources like files, network connections, or database connections are properly closed or released, even if an error occurs during their use.
Releasing Locks or Synchronization Primitives: Ensuring that locks, semaphores, or other synchronization primitives are released, preventing deadlocks and ensuring that other threads or processes can continue to execute.
Cleaning Up After Loop Execution: Executing cleanup code after a loop, whether it completes normally, is interrupted by a break statement, or exits due to an exception.
Ensuring Completion of Critical Steps: Guaranteeing that certain critical steps, like committing a transaction or writing final data, are completed regardless of what happens during the operation.
Logging and Monitoring: Ensuring that logs or monitoring actions are taken, such as recording the end of a process or capturing error information, regardless of whether an error occurred.
📧Join the Python Snacks Newsletter!🐍
Want even more Python-related content that’s useful? Here’s 3 reasons why you should subscribe the Python Snacks newsletter:
Get Ahead in Python with bite-sized Python tips and tricks delivered straight to your inbox, like the one above.
Exclusive Subscriber Perks: Receive a curated selection of up to 6 high-impact Python resources, tips, and exclusive insights with each email.
Get Smarter with Python in under 5 minutes. Your next Python breakthrough could just an email away.
You can unsubscribe at any time.
Interested in starting a newsletter or a blog?
Do you have a wealth of knowledge and insights to share with the world? Starting your own newsletter or blog is an excellent way to establish yourself as an authority in your field, connect with a like-minded community, and open up new opportunities.
If TikTok, Twitter, Facebook, or other social media platforms were to get banned, you’d lose all your followers. This is why you should start a newsletter: you own your audience.
This article may contain affiliate links. Affiliate links come at no cost to you and support the costs of this blog. Should you purchase a product/service from an affiliate link, it will come at no additional cost to you.
Reply