3. Finally

A try statement can also have a finally block. The code in finally runs always: after a successful try, after an except handles an error, and even when a return leaves the function.

  • finally: starts a block that runs no matter what happened before it.
  • Use it for cleanup that must happen, such as closing a resource.
  • finally can appear together with except, or with only try.
  • If an exception is not handled, finally still runs before the program stops.

Coming from JavaScript? finally works the same way in both languages: it runs whether the try succeeds or fails.

#01

Run finally after success

Use a try/finally statement. Inside try, print Open. Inside finally, print Close. No error occurs, so both blocks run.

Print exactly:

Create a free account to save your progress and unlock chapter 2.

#02

Run finally after an error

Use try/except/finally. Inside try, print 10 / 0. Catch ZeroDivisionError and print Error. In finally, print Done.

Print exactly:

Create a free account to save your progress and unlock chapter 2.

#03

Finally runs before return

Define double(number) that returns number * 2 from inside a try block. Add a finally block that prints Finishing. Print double(3). The finally block runs before the function gives the value back to the caller.

Print exactly:

Create a free account to save your progress and unlock chapter 2.

#04

Finally in both paths

Define safe_divide(a, b) that returns a / b inside a try block. Catch ZeroDivisionError and return None. In a finally block, print Done. Print safe_divide(6, 2) and then safe_divide(6, 0).

Print exactly:

Create a free account to save your progress and unlock chapter 2.