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

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.

basics python

For additional information on related topics, take a look at the following resources:


By Leodanis Pozo Ramos • Updated Jan. 6, 2025 • Reviewed by Dan Bader