Programming Search⌘K

Conceptcore

Defer and finally

Also called finally, try-finally, defer, cleanup, with statement, using statement, try-with-resources, scope exit.

Cleanup constructs run code when control leaves a scope, on every path out: the normal end, a return, a break or an exception. Programs use them to close files, release locks and undo partial work.

Applies to
core-languages

Idea

A function that opens a file must close it. If the function has one exit, one call to close at the end is enough. Most functions have more exits than that. An error check returns early, a loop breaks, and an exception leaves from the middle of the body. Each exit must release what the function holds at that point.

The Go blog shows the failure with a function that copies one file to another. The first version opens the source, then creates the destination, and closes both at the end. "If the call to os.Create fails, the function will return without closing the source file."1 The fix with defer puts the close next to the open, and the blog says that the files are then closed "regardless of the number of return statements in the function".1

Every cleanup construct does the same thing. It ties a piece of code to the exit of a scope, so that one statement covers all the paths out. In Python, the code in finally runs on each of the three exits here.

def process(job):
    print("open", job)
    try:
        if job == "empty":
            return "skipped"
        if job == "bad":
            raise ValueError("bad job")
        return "done"
    finally:
        print("close", job)


for job in ["a", "empty", "bad"]:
    try:
        print("->", process(job))
    except ValueError as exc:
        print("-> error:", exc)
Output
open a
close a
-> done
open empty
close empty
-> skipped
open bad
close bad
-> error: bad job

How it works

Languages put the cleanup code in one of three places.

Shape Where the cleanup code is Examples
A block on the exit of a region in a finally block after the body try and finally in Python, JavaScript, Java, C#, Kotlin and PowerShell
A call that the program schedules next to the acquisition, as a function call defer in Go; ExitStack in Python; DisposableStack in JavaScript
A method of the resource in the type of the resource destructors in C++; Drop in Rust; with, using and try-with-resources, which call a method of the object

The three shapes differ in what the programmer must remember. With finally, each function that uses a resource must write the release itself. With a scheduled call, the release is next to the acquisition, but each use must still schedule it. With a destructor, the type writes the release once, and each use gets it without a statement of its own (Resource acquisition is initialization).

The two paths out

Cleanup must run on two kinds of path. On a normal path, control reaches the end of the body or a return, break or continue. On an exceptional path, an exception or a panic passes through the frame (Exception, Panic).

Python describes both paths for finally. If an exception occurs and nothing handles it, the exception "is temporarily saved". The finally clause runs, and the saved exception is raised again at its end. If the finally clause raises another exception, the saved exception becomes the context of the new one.2 A return, break or continue in the try block also runs the finally clause "on the way out".2 JavaScript has the same rule: the effect of a return, throw, break or continue in the try block waits until the finally block ends.3

The statement forms are written in terms of finally. The Python reference gives the with statement as an expansion into try, except and finally that calls the method __exit__ of the context manager. On an exceptional exit, __exit__ receives the exception. If it returns a true value, the exception stops there.4 The C# compiler rewrites a using block into try and finally, so Dispose runs even when the block returns.5 C++ and Rust need no statement at all. The language destroys the objects of a scope when control leaves it. In C++, the objects of a scope are destroyed on exit from the scope "however accomplished".6 During stack unwinding, the objects that a try block constructed are destroyed too.7

Order

When a scope holds several resources, the cleanup runs in reverse order. Each language states this rule.

  • Go runs deferred calls "in the reverse order they were deferred".8
  • Rust drops the variables of a scope "in reverse order of declaration".9
  • C++ destroys the objects of a scope "in the reverse order of their construction".6
  • Java closes the resources of a try-with-resources statement "in the reverse order from that in which they were initialized".10
  • C# disposes several instances of one using statement "in reverse order of declaration".5
  • Python's ExitStack calls its callbacks in reverse order of registration.11

A resource that the program acquires later can depend on an earlier one. A buffered writer depends on the file below it, and a transaction depends on its connection. Reverse order releases each resource while the ones it depends on are still alive. The TypeScript notes give this reason for DisposableStack, which disposes "in a first-in-last-out order".12

Go defer in detail

A Go defer statement has three rules, and the blog lists them.1 The specification states them in full.8

  1. The function value and the arguments of a deferred call are evaluated when the defer statement runs. The call itself waits.
  2. The deferred calls run immediately before the surrounding function returns, in reverse order. They also run when the goroutine panics.
  3. A deferred call runs after a return statement has set the result parameters. A deferred function literal can read and change named results. In the specification, defer func() { result *= 7 }() with return 6 makes the function return 42.

Any results of the deferred function itself are discarded.8 This rule is why defer f.Close() loses the error that Close returns. The Go example uses a deferred function literal and the named result err to keep that error.

The value of a return before finally

A return in the try block computes its value before finally runs. MDN describes this for JavaScript: "the return value expression ... is evaluated before entering the finally block".3 The examples for Python, Java, C# and JavaScript show the same result. Each one assigns a new value to the returned variable in finally, and each function still returns the old value. Go is the exception. Its deferred calls can change named results after return has set them.8

In languages

LanguageVerdictNote
PythonNative
C++Native
JavaNative
CAbsent
C#Native
JavaScriptNative
TypeScriptNative
GoNative
RustNative
KotlinNativeKotlin has try and finally, and the function use closes an AutoCloseable resource when its block completes; no example file because kotlinc is not installed on the machine that recorded the examples.
SQLAbsentA statement has no clause that runs code when it ends. Alternative: The host program releases connections and ends transactions in its own cleanup code.
BashIdiomThe shell has no finally block; trap with the signal EXIT runs a command on exit from the shell. Alternative: Trap 'cleanup' EXIT near the start of the script.
PowerShellNativeA finally block runs after try and catch and can free resources; no example file because pwsh is not installed on the machine that recorded the examples.
HTMLDoes not applyMarkup holds no resources.
CSSDoes not applyStyle rules hold no resources.
Regular expressionsDoes not applyA pattern holds no resources.
Language Verdict Form
Python native try and finally; with and context managers; contextlib.ExitStack
JavaScript native try and finally; using and DisposableStack from Explicit Resource Management
TypeScript native as JavaScript; the types Disposable and DisposableStack
Java native try and finally; try-with-resources with AutoCloseable
C absent no cleanup construct; goto to cleanup labels at the end of the function
C++ native destructors; no finally
C# native try and finally; the using statement and using declarations with IDisposable
Go native defer
Rust native the trait Drop; no finally and no defer
Kotlin native try and finally; the function use for AutoCloseable
PowerShell native try, catch and finally
Bash idiom trap with the signal EXIT
SQL absent a statement has no clause that runs on exit
Regex n/a a pattern holds no resources
HTML/CSS n/a markup and style rules hold no resources

Four families stand out.

  • finally plus a statement form. Python, Java, C#, JavaScript and TypeScript have try and finally, and each adds a statement that calls a cleanup method of an object. Python's with came from PEP 343, which says that it makes it possible "to factor out standard uses of try/finally statements".13 Java's try-with-resources closes each resource and keeps the first exception, with the later ones added as suppressed exceptions.10 C# has the using statement and the using declaration, which disposes its object at the end of the enclosing scope.5 JavaScript's using comes from the proposal Explicit Resource Management, which TC39 lists as finished, with 2027 as its expected year of publication.14 TypeScript 5.2 added using declarations and the types for it.12 Kotlin has finally and the function use, which closes an AutoCloseable resource when its block completes, whether or not the block throws.15 PowerShell has try, catch and finally, and its documentation names the release of resources as a use of finally.16
  • Destructors. C++ and Rust have no finally. The type of the resource releases it in a destructor, which runs on every exit from the scope.69 A small guard type with a function in its destructor gives the effect of defer (see the C++ example).
  • A scheduled call. Go has no finally and no destructors. A defer statement schedules a call for the end of the function.8 The scope of a deferred call is the function, not the block.
  • Nothing. C has none of these constructs. The Linux kernel coding style recommends a goto to a label at the end of the function when a function "exits from multiple locations and some common work such as cleanup has to be done".17 Bash runs a command on exit from the shell with trap ... EXIT.18
PythonGitHub
from contextlib import ExitStack


class File:
    def __init__(self, name):
        self.name = name
        print("open", name)

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc, tb):
        print("close", self.name, "after", exc_type.__name__ if exc_type else "success")
        return False


def copy(src, dst, fail):
    with File(src) as a, File(dst) as b:
        if fail:
            raise OSError(f"cannot read {a.name}")
        print("copy", a.name, "to", b.name)


copy("a.txt", "b.txt", False)
try:
    copy("a.txt", "c.txt", True)
except OSError as exc:
    print("caught:", exc)


def label():
    text = "try"
    try:
        return text
    finally:
        text = "finally"
        print("finally ran; text is now", text)


print("label() returned", label())

with ExitStack() as stack:
    for name in ["x", "y", "z"]:
        stack.callback(print, "release", name)
    print("all acquired")
Output
open a.txt
open b.txt
copy a.txt to b.txt
close b.txt after success
close a.txt after success
open a.txt
open c.txt
close c.txt after OSError
close a.txt after OSError
caught: cannot read a.txt
finally ran; text is now finally
label() returned try
all acquired
release z
release y
release x
  • Verdict: native. try with finally runs cleanup on every exit, and the with statement calls __exit__ of each context manager.
  • A with statement with two items closes them in reverse order, b first and then a. The exception reaches __exit__ and then the caller.
  • The return in label computes its value before finally runs. The assignment in finally does not change the result.
  • ExitStack holds a number of cleanup actions that the program does not know in advance, and calls them in reverse order of registration.

A return in a finally block replaces the return of the try block. Python 3.14 warns about it with a SyntaxWarning when it compiles the code, but the code still runs.

This code runs but gives a wrong answer on purpose.

def save(record):
    try:
        if not record:
            raise ValueError("empty record")
        return "saved"
    finally:
        return "done"


print(save({"id": 1}))
print(save({}))
Output
done
done
#include <functional>
#include <iostream>
#include <stdexcept>
#include <string>
#include <utility>

class File {
public:
    explicit File(std::string name) : name_(std::move(name)) {
        std::cout << "open " << name_ << '\n';
    }
    ~File() { std::cout << "close " << name_ << '\n'; }
    File(const File&) = delete;
    File& operator=(const File&) = delete;
    const std::string& name() const { return name_; }

private:
    std::string name_;
};

class ScopeExit {
public:
    explicit ScopeExit(std::function<void()> f) : f_(std::move(f)) {}
    ~ScopeExit() { f_(); }
    ScopeExit(const ScopeExit&) = delete;
    ScopeExit& operator=(const ScopeExit&) = delete;

private:
    std::function<void()> f_;
};

void copy(const std::string& src, const std::string& dst, bool fail) {
    File a(src);
    File b(dst);
    if (fail) throw std::runtime_error("cannot read " + a.name());
    std::cout << "copy " << a.name() << " to " << b.name() << '\n';
}

int main() {
    copy("a.txt", "b.txt", false);
    try {
        copy("a.txt", "c.txt", true);
    } catch (const std::runtime_error& e) {
        std::cout << "caught: " << e.what() << '\n';
    }
    {
        ScopeExit log([] { std::cout << "scope exit runs last\n"; });
        std::cout << "work in the scope\n";
    }
}
Output
open a.txt
open b.txt
copy a.txt to b.txt
close b.txt
close a.txt
open a.txt
open c.txt
close c.txt
close a.txt
caught: cannot read a.txt
work in the scope
scope exit runs last
  • Verdict: native. C++ has no finally. A destructor runs when an object with automatic storage leaves its scope, on a normal exit and during stack unwinding.
  • Objects are destroyed in reverse order of construction, so b closes before a.
  • ScopeExit is a small class that runs a function in its destructor. It plays the role of defer for code that has no class of its own.

An object without a name is a temporary. The destructor of a temporary runs at the end of the full-expression that creates it, so this lock ends before the work that it should protect.

This code runs but gives a wrong answer on purpose.

#include <iostream>
#include <string>

class Lock {
public:
    explicit Lock(std::string name) : name_(std::move(name)) {
        std::cout << "lock " << name_ << '\n';
    }
    ~Lock() { std::cout << "unlock " << name_ << '\n'; }

private:
    std::string name_;
};

int main() {
    Lock{"accounts"};
    std::cout << "update accounts\n";
    Lock held{"orders"};
    std::cout << "update orders\n";
}
Output
lock accounts
unlock accounts
update accounts
lock orders
update orders
unlock orders
JavaGitHub
public class Main {
    static class File implements AutoCloseable {
        final String name;
        final boolean closeFails;

        File(String name, boolean closeFails) {
            this.name = name;
            this.closeFails = closeFails;
            System.out.println("open " + name);
        }

        @Override
        public void close() {
            System.out.println("close " + name);
            if (closeFails) throw new IllegalStateException("close failed: " + name);
        }
    }

    static void copy(String src, String dst, boolean fail) {
        try (File a = new File(src, false); File b = new File(dst, fail)) {
            if (fail) throw new IllegalStateException("cannot read " + a.name);
            System.out.println("copy " + a.name + " to " + b.name);
        }
    }

    static String label() {
        String text = "try";
        try {
            return text;
        } finally {
            text = "finally";
            System.out.println("finally ran; text is now " + text);
        }
    }

    public static void main(String[] args) {
        copy("a.txt", "b.txt", false);
        try {
            copy("a.txt", "c.txt", true);
        } catch (IllegalStateException e) {
            System.out.println("caught: " + e.getMessage());
            for (Throwable s : e.getSuppressed()) {
                System.out.println("suppressed: " + s.getMessage());
            }
        }
        System.out.println("label() returned " + label());
    }
}
Output
open a.txt
open b.txt
copy a.txt to b.txt
close b.txt
close a.txt
open a.txt
open c.txt
close c.txt
close a.txt
caught: cannot read a.txt
suppressed: close failed: c.txt
finally ran; text is now finally
label() returned try
  • Verdict: native. try with finally runs on every exit. A try-with-resources statement closes each AutoCloseable resource in reverse order of initialization.
  • When the body throws and close also throws, the statement keeps the exception from the body and adds the one from close as a suppressed exception.
  • The return in label computes its value before finally runs, so the assignment in finally does not change the result.

With a plain finally, an exception from close replaces the exception from the body. The caller sees only the second failure, and the first one is lost.

This code runs but gives a wrong answer on purpose.

public class Main {
    static void close(String name) {
        throw new IllegalStateException("close failed: " + name);
    }

    static void copy(String src) {
        try {
            throw new IllegalStateException("cannot read " + src);
        } finally {
            close(src);
        }
    }

    public static void main(String[] args) {
        try {
            copy("a.txt");
        } catch (IllegalStateException e) {
            System.out.println("caught: " + e.getMessage());
            System.out.println("suppressed: " + e.getSuppressed().length);
        }
    }
}
Output
caught: close failed: a.txt
suppressed: 0

A return in finally discards the exception of the try block. javac compiles this code without an error.

This code runs but gives a wrong answer on purpose.

public class Main {
    static String save(String record) {
        try {
            if (record.isEmpty()) throw new IllegalArgumentException("empty record");
            return "saved";
        } finally {
            return "done";
        }
    }

    public static void main(String[] args) {
        System.out.println(save("id=1"));
        System.out.println(save(""));
    }
}
Output
done
done
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

static int open_count = 0;

static char *open_file(const char *name) {
    printf("open %s\n", name);
    open_count++;
    return strdup(name);
}

static void close_file(char *f) {
    printf("close %s\n", f);
    open_count--;
    free(f);
}

static int copy(const char *src, const char *dst, int fail) {
    int result = -1;
    char *a = open_file(src);
    if (a == NULL)
        goto out;
    char *b = open_file(dst);
    if (b == NULL)
        goto out_close_a;
    if (fail) {
        printf("cannot read %s\n", a);
        goto out_close_b;
    }
    printf("copy %s to %s\n", a, b);
    result = 0;
out_close_b:
    close_file(b);
out_close_a:
    close_file(a);
out:
    return result;
}

int main(void) {
    printf("result %d\n", copy("a.txt", "b.txt", 0));
    printf("result %d\n", copy("a.txt", "c.txt", 1));
    printf("files open: %d\n", open_count);
    return 0;
}
Output
open a.txt
open b.txt
copy a.txt to b.txt
close b.txt
close a.txt
result 0
open a.txt
open c.txt
cannot read a.txt
close c.txt
close a.txt
result -1
files open: 0
  • Verdict: absent. C has no finally, no defer and no destructors. The cleanup code is written by hand.
  • Each exit path jumps with goto to a label at the end of the function. The labels release the resources in reverse order of acquisition, and each label releases one resource.
  • The Linux kernel coding style recommends this form and asks for label names that say what the label releases.

A return in the middle of the function skips the cleanup code. The program loses track of an open file.

This code runs but gives a wrong answer on purpose.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

static int open_count = 0;

static char *open_file(const char *name) {
    open_count++;
    return strdup(name);
}

static void close_file(char *f) {
    open_count--;
    free(f);
}

static int copy(const char *src, int fail) {
    char *a = open_file(src);
    if (fail)
        return -1;
    printf("copy %s\n", a);
    close_file(a);
    return 0;
}

int main(void) {
    copy("a.txt", 0);
    copy("b.txt", 1);
    printf("files open: %d\n", open_count);
    return 0;
}
Output
copy a.txt
files open: 1
using System;

static void Copy(string src, string dst, bool fail)
{
    using var a = new FakeFile(src);
    using var b = new FakeFile(dst);
    if (fail) throw new InvalidOperationException($"cannot read {a.Name}");
    Console.WriteLine($"copy {a.Name} to {b.Name}");
}

static string Label()
{
    string text = "try";
    try
    {
        return text;
    }
    finally
    {
        text = "finally";
        Console.WriteLine($"finally ran; text is now {text}");
    }
}

Copy("a.txt", "b.txt", false);
try
{
    Copy("a.txt", "c.txt", true);
}
catch (InvalidOperationException e)
{
    Console.WriteLine($"caught: {e.Message}");
}
Console.WriteLine($"Label() returned {Label()}");

sealed class FakeFile : IDisposable
{
    public string Name { get; }

    public FakeFile(string name)
    {
        Name = name;
        Console.WriteLine($"open {name}");
    }

    public void Dispose() => Console.WriteLine($"close {Name}");
}
Output
open a.txt
open b.txt
copy a.txt to b.txt
close b.txt
close a.txt
open a.txt
open c.txt
close c.txt
close a.txt
caught: cannot read a.txt
finally ran; text is now finally
Label() returned try
  • Verdict: native. try with finally runs on every exit. A using declaration disposes its object at the end of the enclosing scope, and several objects are disposed in reverse order of declaration.
  • The compiler turns using into try and finally, so a return or an exception in the scope still calls Dispose.
  • The return in Label computes its value before finally runs.

C# does not let control leave a finally block. A return there is the compile error CS0157, so the bug of the other languages cannot be written.

This code does not compile, on purpose.

using System;

static string Save(string record)
{
    try
    {
        if (record.Length == 0) throw new ArgumentException("empty record");
        return "saved";
    }
    finally
    {
        return "done";
    }
}

Console.WriteLine(Save(""));
JavaScriptGitHub
class File {
  constructor(name) {
    this.name = name;
    console.log("open", name);
  }
  [Symbol.dispose]() {
    console.log("close", this.name);
  }
}

function copy(src, dst, fail) {
  using a = new File(src);
  using b = new File(dst);
  if (fail) throw new Error(`cannot read ${a.name}`);
  console.log("copy", a.name, "to", b.name);
}

copy("a.txt", "b.txt", false);
try {
  copy("a.txt", "c.txt", true);
} catch (e) {
  console.log("caught:", e.message);
}

function label() {
  let text = "try";
  try {
    return text;
  } finally {
    text = "finally";
    console.log("finally ran; text is now", text);
  }
}
console.log("label() returned", label());
Output
open a.txt
open b.txt
copy a.txt to b.txt
close b.txt
close a.txt
open a.txt
open c.txt
close c.txt
close a.txt
caught: cannot read a.txt
finally ran; text is now finally
label() returned try
  • Verdict: native. try with finally runs on every exit. A using declaration calls [Symbol.dispose]() when the block ends, in reverse order of declaration.
  • using comes from the proposal Explicit Resource Management, which reached stage 4 at TC39. Its expected year of publication in the standard is 2027. Node.js 26 runs it.
  • The return in label evaluates text before finally runs, so the change in finally does not change the result.

A return in finally overrides the return or the throw of the try block. The error in the second call disappears.

This code runs but gives a wrong answer on purpose.

function save(record) {
  try {
    if (!record) throw new Error("empty record");
    return "saved";
  } finally {
    return "done";
  }
}

console.log(save({ id: 1 }));
console.log(save(null));
Output
done
done
TypeScriptGitHub
class File implements Disposable {
  readonly name: string;
  constructor(name: string) {
    this.name = name;
    console.log("open", name);
  }
  [Symbol.dispose](): void {
    console.log("close", this.name);
  }
}

function copy(src: string, dst: string, fail: boolean): void {
  using a = new File(src);
  using b = new File(dst);
  if (fail) throw new Error(`cannot read ${a.name}`);
  console.log("copy", a.name, "to", b.name);
}

copy("a.txt", "b.txt", false);
try {
  copy("a.txt", "c.txt", true);
} catch (e) {
  console.log("caught:", (e as Error).message);
}

{
  using cleanup = new DisposableStack();
  for (const n of ["x", "y", "z"]) {
    cleanup.defer(() => console.log("release", n));
  }
  console.log("all acquired");
}
Output
open a.txt
open b.txt
copy a.txt to b.txt
close b.txt
close a.txt
open a.txt
open c.txt
close c.txt
close a.txt
caught: cannot read a.txt
all acquired
release z
release y
release x
  • Verdict: native. TypeScript 5.2 added using declarations and the types Disposable and DisposableStack.
  • DisposableStack collects cleanup actions whose number is known only at run time. Its method defer takes a callback, and the stack calls the callbacks in reverse order when it is disposed. The TypeScript notes compare it with the keyword defer in Go.
  • try and finally work as in JavaScript, including the pitfall of a return in finally.
package main

import (
	"errors"
	"fmt"
)

type file struct {
	name    string
	failure error
}

func open(name string) *file {
	fmt.Println("open", name)
	return &file{name: name}
}

func (f *file) Close() error {
	fmt.Println("close", f.name)
	return f.failure
}

func copyFile(src, dst string, closeFails bool) (err error) {
	in := open(src)
	defer in.Close()
	out := open(dst)
	if closeFails {
		out.failure = errors.New("disk full")
	}
	defer func() {
		if cerr := out.Close(); cerr != nil && err == nil {
			err = fmt.Errorf("close %s: %w", dst, cerr)
		}
	}()
	fmt.Println("copy", src, "to", dst)
	return nil
}

func main() {
	fmt.Println("result:", copyFile("a.txt", "b.txt", false))
	fmt.Println("result:", copyFile("a.txt", "c.txt", true))

	for i := 0; i <= 3; i++ {
		defer fmt.Print(i, " ")
	}
	fmt.Print("deferred: ")
}
Output
open a.txt
open b.txt
copy a.txt to b.txt
close b.txt
close a.txt
result: <nil>
open a.txt
open c.txt
copy a.txt to c.txt
close c.txt
close a.txt
result: close c.txt: disk full
deferred: 3 2 1 0
  • Verdict: native. A defer statement schedules a call to run when the function returns, whether by return, by the end of the body or by a panic.
  • The deferred calls run in reverse order. out closes before in, and the loop prints 3 2 1 0.
  • A deferred function literal can read and change the named result err. Here it reports the error from Close, which a plain defer out.Close() would discard.

A deferred call evaluates its arguments when the defer statement runs, not when the call runs. The program means to print the final count, but it prints the count at the time of the defer.

This code runs but gives a wrong answer on purpose.

package main

import "fmt"

func main() {
	count := 0
	defer fmt.Println("processed", count, "items")
	for i := 0; i < 3; i++ {
		count++
	}
	fmt.Println("count is", count)
}
Output
count is 3
processed 0 items

A defer inside a loop does not run at the end of each iteration. It runs when the function returns, so every file in the loop stays open until then.

This code runs but gives a wrong answer on purpose.

package main

import "fmt"

var openFiles, maxOpen int

type file struct{ name string }

func open(name string) *file {
	openFiles++
	if openFiles > maxOpen {
		maxOpen = openFiles
	}
	return &file{name}
}

func (f *file) Close() { openFiles-- }

func processAll(names []string) {
	for _, name := range names {
		f := open(name)
		defer f.Close()
	}
	fmt.Println("open at the end of the loop:", openFiles)
}

func main() {
	names := make([]string, 1000)
	for i := range names {
		names[i] = fmt.Sprintf("log-%d.txt", i)
	}
	processAll(names)
	fmt.Println("most files open at once:", maxOpen)
}
Output
open at the end of the loop: 1000
most files open at once: 1000
RustGitHub
struct File {
    name: String,
}

impl File {
    fn open(name: &str) -> File {
        println!("open {name}");
        File { name: name.to_string() }
    }
}

impl Drop for File {
    fn drop(&mut self) {
        println!("close {}", self.name);
    }
}

fn copy(src: &str, dst: &str, fail: bool) -> Result<(), String> {
    let a = File::open(src);
    let b = File::open(dst);
    if fail {
        return Err(format!("cannot read {}", a.name));
    }
    println!("copy {} to {}", a.name, b.name);
    Ok(())
}

fn main() {
    println!("result: {:?}", copy("a.txt", "b.txt", false));
    println!("result: {:?}", copy("a.txt", "c.txt", true));

    let result = std::panic::catch_unwind(|| {
        let _guard = File::open("d.txt");
        panic!("bug while d.txt is open");
    });
    println!("panicked: {}", result.is_err());

    let early = File::open("e.txt");
    drop(early);
    println!("e.txt is closed before the end of main");
}
Output
open a.txt
open b.txt
copy a.txt to b.txt
close b.txt
close a.txt
result: Ok(())
open a.txt
open c.txt
close c.txt
close a.txt
result: Err("cannot read a.txt")
open d.txt
close d.txt
panicked: true
open e.txt
close e.txt
e.txt is closed before the end of main
  • Verdict: native. A type that implements Drop runs its drop method when its value goes out of scope. This covers a normal return, an early return with ? or return, and unwinding after a panic.
  • Variables are dropped in reverse order of declaration, so b closes before a.
  • drop(value) ends the life of a value before the end of its scope.
  • Rust has no finally and no defer. A guard value with Drop does that work.

The pattern _ does not bind the value. The guard is a temporary, and it is dropped at the end of the statement, before the work that it should protect.

This code runs but gives a wrong answer on purpose.

struct Lock(&'static str);

impl Drop for Lock {
    fn drop(&mut self) {
        println!("unlock {}", self.0);
    }
}

fn lock(name: &'static str) -> Lock {
    println!("lock {name}");
    Lock(name)
}

fn main() {
    let _ = lock("accounts");
    println!("update accounts");
    let _held = lock("orders");
    println!("update orders");
}
Output
lock accounts
unlock accounts
update accounts
lock orders
update orders
unlock orders

std::mem::forget takes ownership of a value and does not run its destructor. It is a safe function, so code must not depend on drop for memory safety.

This code runs but gives a wrong answer on purpose.

struct File(&'static str);

impl Drop for File {
    fn drop(&mut self) {
        println!("close {}", self.0);
    }
}

fn main() {
    let a = File("a.txt");
    let b = File("b.txt");
    std::mem::forget(a);
    drop(b);
    println!("end of main");
}
Output
close b.txt
end of main
  • Cleanup lists. Some resources are known only at run time, such as one file for each name in a list. ExitStack in Python and DisposableStack in JavaScript keep a stack of cleanup actions and run all of them when the stack is closed.1112 The TypeScript notes compare the method defer of DisposableStack with the keyword defer in Go.12
  • Asynchronous cleanup. A cleanup that must wait for I/O needs an asynchronous form. Python has async with, which can be used only in a coroutine function.19 JavaScript has await using declarations and AsyncDisposableStack.12
  • Cleanup that fails. Closing a file can fail, and the failure can collide with an earlier one. With a plain finally in Java, an exception from close wins, and "the exception thrown from the try block is suppressed".20 Java's try-with-resources keeps the first exception and adds the others as suppressed exceptions.10 Python sets the saved exception as the context of the new one.2 Go discards the results of a deferred call unless the code passes them on by hand.8
  • Scope guards. A guard object that runs a function in its destructor turns the destructor shape into a scheduled call. The C++ example builds one in a few lines. A function that takes a callback for the body and closes the resource after it is another form (Higher-order function, Closure).

Pitfalls

A return in finally

A return in finally replaces whatever the try block was doing. MDN says that a control flow statement at the end of finally "will override the effect of the previous one".3 It replaces a return, and it also replaces a throw, so the error disappears.

This code runs but gives a wrong answer on purpose.

function save(record) {
  try {
    if (!record) throw new Error("empty record");
    return "saved";
  } finally {
    return "done";
  }
}

console.log(save({ id: 1 }));
console.log(save(null));
Output
done
done

Python behaves the same way.2 PEP 765 measured the pattern in real code. It is rare, about 2 uses per million lines in the top 8,000 PyPI packages, and "most of the usages are incorrect".21 Python 3.14 emits a SyntaxWarning for it.21 Java compiles it, and the abrupt end of finally discards the exception.22 C# rejects it with the compile error CS0157, "Control cannot leave the body of a finally clause".23 Exception shows the effect on the exception in more detail. The fix is to keep finally for cleanup and to put the return after the try statement.

A change in finally that does not change the result

A function that assigns to its returned variable in finally still returns the old value, because the return computed its value first.3 The examples for Python, Java, C# and JavaScript show it. To change the result of a function on its way out, Go uses a named result and a deferred function literal.8 Other languages need the change before the return.

Deferred arguments are evaluated at once

Go evaluates the arguments of a deferred call when the defer statement runs.8 defer fmt.Println("processed", count) prints the value of count at that point, not at the end (see the arguments block of the Go example). To read the value at the end, defer a function literal that reads the variable.

Defer in a loop

A deferred call runs when the function returns, not at the end of the loop body.8 A loop that opens a file and defers its close keeps every file open until the function ends. The loop block of the Go example opens 1000 files and holds all of them at once. The fix is to move the body of the loop into a function of its own, so that each call closes its file.

A guard without a name

In Rust, the pattern _ does not bind the value that it matches.24 let _ = lock() creates a temporary, and Rust drops the temporaries of a statement at the end of that statement.9 The lock ends before the next line. In C++, Lock{"accounts"}; creates a temporary, and a temporary is destroyed "as the last step in evaluating the full-expression" that contains it.25 The underscore block of the Rust example and the temporary block of the C++ example show both. Give the guard a name, such as _held or held.

Cleanup that does not run

Cleanup constructs run when control leaves a scope. A process that ends at once does not leave its scopes. Python's os._exit exits "without calling cleanup handlers".26 The Python example of Panic shows a finally block that does not run after os._exit. Rust also lets safe code skip a destructor: std::mem::forget is a safe function, and the reference says that types "may not safely rely on a destructor being run for soundness".9

The wrong label in C

With goto cleanup, each label must release only what is already acquired on every path that jumps to it. The kernel style guide calls the error "one err bugs": a single label err frees foo->bar and then foo, but on some paths foo is NULL. The fix is one label for each resource, in reverse order.17 A return in the middle of the function skips all the labels (see the early-return block of the C example).

Cost

  • The cleanup code. A cleanup construct runs the same release code that a programmer would write on each path. The source has one copy of that code in place of one copy for each path.
  • Go defer. The Go 1.14 release notes say that most uses of defer "incur almost zero overhead compared to calling the deferred function directly".27
  • Cleanup lists. ExitStack and DisposableStack keep one entry for each registered action, and they call the actions one at a time when they close.1112
  • Resources held too long. The resource stays held until the scope ends. A C# using declaration holds its object to the end of the enclosing scope, and a using statement holds it only for its block.5 Rust's drop(value) and a short with block in Python release a resource earlier. A defer in a loop holds every resource until the function returns.

History

  • 2005. PEP 343 by Guido van Rossum and Alyssa Coghlan proposed the with statement for Python 2.5. Its stated aim was to factor out standard uses of try and finally.13
  • 2010. Andrew Gerrand's post "Defer, Panic, and Recover" on the Go blog explained defer with the file copy that leaks a file, and gave the three rules of defer.1
  • 2024. PEP 765 by Irit Katriel and Alyssa Coghlan proposed a warning for return, break and continue that leave a finally block. Python 3.14 emits it as a SyntaxWarning.21

References

  1. Andrew Gerrand, "Defer, Panic, and Recover", The Go Blog, 4 August 2010, the CopyFile example and the three rules of defer
  2. The Python Language Reference (3.14), 8. Compound statements, 8.4.4 finally clause
  3. MDN Web Docs, try...catch, the description of the finally block and the example Returning from a finally block
  4. The Python Language Reference (3.14), 8. Compound statements, 8.5 The with statement, the expansion into try, except and finally
  5. C# language reference, The using statement, the sections on using declarations and on several instances
  6. Working Draft, Programming Languages, C++ (N4950, the C++23 draft), [stmt.jump.general] 8.7.1, paragraph 2 (Note 1)
  7. Working Draft, Programming Languages, C++ (N4950, the C++23 draft), [except.ctor] 14.3 Constructors and destructors, paragraphs 1 and 2
  8. The Go Programming Language Specification, Defer statements
  9. The Rust Reference, Destructors, destructors.intro, the drop scopes, destructors.scope.temporary and destructors.forget
  10. The Java Language Specification, Java SE 25 Edition, 14.20.3 try-with-resources and 14.20.3.1 Basic try-with-resources
  11. Python 3.14 documentation, contextlib, class contextlib.ExitStack
  12. TypeScript 5.2 release notes, using Declarations and Explicit Resource Management
  13. Guido van Rossum and Alyssa Coghlan, PEP 343, The "with" Statement, the header (Created 13-May-2005, Python-Version 2.5) and the abstract
  14. TC39, Finished Proposals, the row Explicit Resource Management (Ron Buckton, expected publication year 2027)
  15. Kotlin documentation, Exceptions, The finally block; the use() function
  16. PowerShell documentation, about_Try_Catch_Finally, Long description
  17. Linux kernel coding style, 7) Centralized exiting of functions
  18. bash(1), Linux manual page, SHELL BUILTIN COMMANDS, trap ("If a sigspec is EXIT (0), action is executed on exit from the shell")
  19. The Python Language Reference (3.14), 8. Compound statements, 8.9.3 The async with statement
  20. The Java Tutorials, The try-with-resources Statement, the example readFirstLineFromFileWithFinallyBlock and Suppressed Exceptions
  21. Irit Katriel and Alyssa Coghlan, PEP 765, Disallow return/break/continue that exit a finally block, the header (Created 15-Nov-2024, Python-Version 3.14) and Rationale
  22. The Java Language Specification, Java SE 25 Edition, 14.20.2 Execution of try-finally and try-catch-finally
  23. C# reference, Resolve errors and warnings related to jump statements, CS0157: Control cannot leave the body of a finally clause
  24. The Rust Reference, Patterns, patterns.wildcard.no-binding
  25. Working Draft, Programming Languages, C++ (N4950, the C++23 draft), [class.temporary] paragraph 4
  26. Python 3.14 documentation, os, os._exit
  27. Go 1.14 Release Notes, Runtime

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/TG9ME7/text.yaml