finally keyword in Python

  • Last updated Apr 25, 2024

Python provides the finally keyword, which can be optionally used with a try and except block to define a code block that always executes, regardless of whether an exception is raised. The finally keyword is typically used to free resources, such as closing database connections, closing files after reading, etc, regardless of whether an exception occurs.

Here's how the finally keyword is used in Python:

try:
    # Code that may raise an exception
except Exception:
    # Code to handle the exception
finally:
    # Code that always executes, whether there was an exception or not

The finally block is optional, however when used, it guarantees that the specified code will run, making it useful for releasing resources, closing files, or performing cleanup tasks. Here's an example:

try:
    file = open("example.txt", "r")
    data = file.read()
except FileNotFoundError:
    print("File not found")
finally:
    if 'file' in locals():
        file.close()
    print("File closed, whether there was an exception or not.")

In this example, the code inside the finally block will always execute, ensuring that the file is closed. This is important for maintaining resource integrity and avoiding resource leaks in your program.