Back
+10 XP
Concept

The `finally` Block: Guaranteed Cleanup

`finally:` runs NO MATTER WHAT—whether an exception happened, was caught, or wasn't. Use it for closing files and network sockets.

python
try:
    print("Connecting...")
    val = 10 / 0
except ZeroDivisionError:
    print("Caught error!")
finally:
    print("Always cleaned up.")

# 112. The `finally` Block: Guaranteed Cleanup `finally:` runs NO MATTER WHAT—whether an exception happened, was caught, or wasn't. Use it for closing files and network sockets: ```python try: print("Connecting...") val = 10 / 0 except ZeroDivisionError: print("Caught error!") finally: print("Always cleaned up.") ``` Even if you type `return` inside the `try` block, Python pauses the return, runs the code inside `finally`, and only then hands control back to the caller.

Checkpoint

Does the `finally` block run if an exception crashes the program?

Practice

Write a `try/finally` block. Inside `try:`, print `"Task started"`. Inside `finally:`, print `"Always executed"`.

Terminal
01
Tap code blocks below to assemble
Available Blocks