finally
In Python, the finally
keyword is used in a try
statement to define a block of code that will always execute, regardless of whether an exception was raised. This keyword is especially useful for cleaning up resources or performing any necessary finalization tasks.
Python finally
Keyword Examples
Here’s a quick example of using the finally
keyword to work with temporary files:
Python
>>> from pathlib import Path
>>> import tempfile
>>> def process_temp_file():
... temp_path = Path(tempfile.NamedTemporaryFile(delete=False).name)
... try:
... print(f"Using temporary file: {temp_path}")
... temp_path.write_bytes(b"Hello from temporary file!")
... # Simulate an error
... raise RuntimeError("Processing failed!")
... finally:
... print(f"Deleting temporary file: {temp_path}")
... temp_path.unlink()
...
>>> process_temp_file()
Using temporary file: /var/folders/dg/...
Deleting temporary file: /var/folders/dg/...
Traceback (most recent call last):
...
RuntimeError: Processing failed!
When working with temporary files, the finally
clause allows you to delete the file even if an error occurs during processing.
Python finally
Keyword Use Cases
- Ensuring that resources such as files or network connections are properly closed or released
- Performing cleanup tasks that must run regardless of whether an exception occurs
- Writing code that should execute after a
try
block, even if no exceptions are raised
Related Resources
Tutorial
Python Exceptions: An Introduction
In this beginner tutorial, you'll learn what exceptions are good for in Python. You'll see how to raise exceptions and how to handle them with try ... except blocks.
For additional information on related topics, take a look at the following resources:
- Python's Built-in Exceptions: A Walkthrough With Examples (Tutorial)
- How to Catch Multiple Exceptions in Python (Tutorial)
- Introduction to Python Exceptions (Course)
- Raising and Handling Python Exceptions (Course)
- Python Exceptions: An Introduction (Quiz)
- Python's Built-in Exceptions: A Walkthrough With Examples (Quiz)