In Python, what keyword is used in a try block to define cleanup code that always runs?

The story behind the answer

In Python, the `finally` keyword defines cleanup code that runs whenever control leaves the associated `try` statement. It runs whether the protected code finishes normally, raises an exception, or is handled by an `except` clause.

A typical use is closing a file, releasing a lock, or disconnecting from a service. Python also provides the `with` statement for many resource-management tasks, but `finally` remains useful when cleanup must be expressed directly around exception-handling logic.

The `else` clause is different: it runs only when the `try` block completes without raising an exception. `except` handles matching exceptions; it does not mean cleanup code. Python’s `finally` suite can even run when a function returns from inside the `try` or `except` block, because the interpreter performs the cleanup before completing the return.

There are extreme process-level failures—such as power loss or an abrupt termination—that can prevent any cleanup code from running. Under ordinary Python control flow, however, `finally` is the construct associated with guaranteed cleanup on leaving the `try` statement.

Source: Wikipedia · fact-checked Aug. 2026

Add question to a list

Choose a list to keep this question in: