Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

Keyword finally

Run cleanup when control leaves the associated try, including through return or exception.

Version: Python 3.14; repository image, production runtime not attested

Syntax

try:
    ...
finally:
    ...

Run cleanup when control leaves the associated try, including through return or exception.

A pending return expression is evaluated before cleanup. An exception from finally can replace a pending exception while retaining the original as its context.

Python 3.14 emits SyntaxWarning for return, break or continue that exits a finally suite.

Examples

def read(log):
    try:
        log.append("read")
        return len(log)
    finally:
        log.append("closed")
log = []
print(read(log), log)
try:
    try:
        raise KeyError("old")
    finally:
        raise ValueError("new")
except ValueError as error:
    print(type(error.__context__).__name__)

Result

1 ['read', 'closed']
KeyError

Python 3.14 emits SyntaxWarning for return, break or continue that exits a finally suite.

Sources