Why do we need the "finally" clause in Python?

Why do we need the “finally” clause in Python?

I’m not sure about the necessity of the “finally” clause in a try…except…finally statement. In my understanding, this code:

try:
    run_code1()
except TypeError:
    run_code2()
other_code()

seems similar to this one that uses the “finally” clause:

try:
    run_code1()
except TypeError:
    run_code2()
finally:
    other_code()

Am I missing something here regarding the use of Python try finally?

The finally block ensures that certain code runs no matter what, even if an exception is raised. Without the finally clause, if an exception occurs and isn’t caught, the code after except will not execute. In contrast, with finally, the code will always run, regardless of whether an exception is raised or not.

Example:

try:
    run_code1()
except TypeError:
    run_code2()
finally:
    other_code()  # Always runs, even if an exception is raised

The finally block is often used for cleanup actions, such as closing files or releasing resources. If you want to make sure these actions occur no matter what (even if an exception was raised or not), using the finally clause is the best approach.

Example:

try:
    file = open('data.txt', 'r')
    # Some code that could raise an exception
except IOError:
    print("Error reading the file")
finally:
    file.close()  # Ensures that the file is always closed

If you return a value from within a try or except block, the finally block will still execute before the function returns. This is crucial for running necessary cleanup, even when returning early.

Example:

def example():
    try:
        return "Success"
    except TypeError:
        return "Error"
    finally:
        print("This will always run")

print(example())  # Output will include "This will always run"

The Python try finally mechanism is critical for ensuring that important code is always executed, even when exceptions occur or when returning from a function.