Python Glossary Русский

all Python 3Exceptionsconstruct

finally

handling

The finally block always runs — whether or not an exception was raised. Used to release resources.

Syntax

try:
    ...
finally:
    cleanup()

The main trap is a return, break or continue inside finally itself: it swallows the exception in flight and overrides the value from try, so a failure disappears without a trace — Python 3.14 flags this with a SyntaxWarning. finally also runs when you leave via return: the value is computed first, then finally runs, and only then does the function actually return. For files, sockets and locks prefer with — a context manager does the same job with less room to forget the cleanup.

Examples

def read_file(path):
    f = None
    try:
        f = open(path)
        return f.read()
    except FileNotFoundError:
        return None
    finally:
        if f:
            f.close()
        print('File handle closed')  # печатается всегда — и при успехе, и при ошибке
def divide(a, b):
    try:
        return a / b
    finally:
        print('division attempted')  # → division attempted
print(divide(10, 2))  # → 5.0
# finally при return
def func():
    try:
        return 'try'
    finally:
        return 'finally'  # перекрывает return из try!
print(func())  # → finally
# finally при raise
def func2():
    try:
        raise ValueError('oops')
    finally:
        print('cleanup')  # → cleanup (до распространения исключения)
try:
    func2()
except ValueError:
    pass
# Классический паттерн с ресурсом
import sqlite3
conn = None
try:
    conn = sqlite3.connect(':memory:')
except Exception as e:
    print(e)
finally:
    if conn:
        conn.close()
        print('Connection closed')  # → Connection closed

See also

Open in the full glossarydocs.python.orgReport an inaccuracy