🚀 LEVEL UP TO SENIOR:Unlock 500+ Advanced Practical Challenges & Exercises.
🎓 COURSERA PARTNER:Earn professional Google, Meta, and IBM certificates to supercharge your resume.
REFERENCEpython

python Documentation

LOADING ENGINE...

finally Block

AI & DATA SCIENCE // finally-block

The finally block always runs after a try statement, whether or not an exception occurred, and even if the exception was never caught.

Syntax

try:
    risky_code()
except SomeError:
    handle_it()
finally:
    always_runs()

Deep Dive Course

finally is guaranteed to execute no matter what happens in the try block — if the code succeeds, if an exception is caught by an except clause, if an exception is raised and not caught (finally still runs before the exception propagates further), and even if the try block hits a return, break, or continue. This makes it the right place for cleanup code that absolutely must happen, like closing a file or releasing a lock, regardless of how the rest of the block turned out.

1Understanding finally Block

finally is guaranteed to execute no matter what happens in the try block — if the code succeeds, if an exception is caught by an except clause, if an exception is raised and not caught (finally still runs before the exception propagates further), and even if the try block hits a return, break, or continue. This makes it the right place for cleanup code that absolutely must happen, like closing a file or releasing a lock, regardless of how the rest of the block turned out.

💡

A return inside a finally block will silently override any return value, or even an in-flight exception, from the try/except above it — this is almost always a bug, so avoid returning from inside finally.

editor.html
def process():
    try:
        print("Working...")
        raise ValueError("Something broke")
    except ValueError:
        print("Handled the error")
    finally:
        print("Cleanup always runs")

process()
localhost:3000

2Practical Example

Here is a real-world application of finally Block showing how it is used in production Python code.

editor.html
lock_acquired = False
try:
    lock_acquired = True
    print("Doing critical work")
finally:
    if lock_acquired:
        print("Releasing lock")
localhost:3000

3Best Practices

Follow these guidelines when working with finally Block:

1. Use finally for cleanup that must always happen, like closing a file, releasing a lock, or closing a network connection

2. Prefer a with statement/context manager over a manual try/finally for cleanup whenever the resource supports it, since it's less error-prone

3. Never put a return, break, or continue inside a finally — it silently discards whatever exception or return value was already in progress

⚠️

Tip: A return inside a finally block will silently override any return value, or even an in-flight exception, from the try/except above it — this is almost always a bug, so avoid returning from inside finally.

editor.html
def process():
    try:
        print("Working...")
        raise ValueError("Something broke")
    except ValueError:
        print("Handled the error")
    finally:
        print("Cleanup always runs")

process()
localhost:3000

Examples

Example 01Basic Usage
def process():
    try:
        print("Working...")
        raise ValueError("Something broke")
    except ValueError:
        print("Handled the error")
    finally:
        print("Cleanup always runs")

process()
Example 02Advanced Example
lock_acquired = False
try:
    lock_acquired = True
    print("Doing critical work")
finally:
    if lock_acquired:
        print("Releasing lock")

Best Practices

  • Use finally for cleanup that must always happen, like closing a file, releasing a lock, or closing a network connection
  • Prefer a with statement/context manager over a manual try/finally for cleanup whenever the resource supports it, since it's less error-prone
  • Never put a return, break, or continue inside a finally — it silently discards whatever exception or return value was already in progress

Interview Question

If an exception is raised in a try block and not caught by any except clause, does the finally block still run before the exception propagates up?

Hint: Think about finally's guarantee.

Yes — finally always runs, regardless of whether the exception was caught. If no except clause matches, Python still executes the finally block completely first, and only then lets the exception continue propagating up to the calling code. This guarantee is exactly what makes finally reliable for cleanup logic that must run under every possible outcome, not just the ones your except clauses happen to catch.

Exercises

MediumPractice using finally Block in a real scenario.
View Solution
def process():
    try:
        print("Working...")
        raise ValueError("Something broke")
    except ValueError:
        print("Handled the error")
    finally:
        print("Cleanup always runs")

process()

Frequently Asked Questions

If an exception is raised in a try block and not caught by any except clause, does the finally block still run before the exception propagates up?

Yes — finally always runs, regardless of whether the exception was caught. If no except clause matches, Python still executes the finally block completely first, and only then lets the exception continue propagating up to the calling code. This guarantee is exactly what makes finally reliable for cleanup logic that must run under every possible outcome, not just the ones your except clauses happen to catch.

Related Functions

try-blockexcept-blockwith-statement