← Fundamentals
Fundamentals

Cleanup on a failing path

Which resource owners survive the work, and what releases them after a failure?

Cleanup must cover the resource’s whole use and every ordinary or failing exit from that work.

Outcome

Keep a resource available through its work, arrange release on the covered return and propagated-failure paths, and release only acquired resources in the order their dependencies require.

Terminology (4)Terms used in this lesson

Term on the front, definition on the back. Paste with tabs between fields and a new line between cards, or import the download in Anki as Basic.

Cleanup
Releasing an acquired resource, such as a scratch-buffer lease, file or destination lock.
Early exit
A return or failure path that leaves before the function’s final ordinary statement.
Reverse order
Ending acquired resources from the most recently acquired to the earliest.
RAII
A resource lifetime tied to an object’s construction and destruction.

Tie cleanup to the work that owns a resource

Acquiring a resource creates a release responsibility: return a leased buffer, unlock a lock or close a file. Identify which operation owns that responsibility and how long its work needs the resource. A release placed only after successful work can miss an earlier exit.

RAII puts release in an owning object’s destructor. A retained automatic owner can cover normal return and exception unwinding. The owner must remain alive for the work it protects; an aborting process does not provide the same cleanup path.

01Early exits

A failure can skip a release at the function end

A configuration importer borrows scratch storage to decode each key=value entry before writing it to a destination cache. A malformed entry can leave that storage leased after its caller has already reported failure. The importer also needs to acquire a destination lock and keep a batch moving after one bad record.

The importer stores port=8080 and then attempts malformed badline. The decoder reads the actual leased working text. Track which pool entries remain after those calls leave.

storeAssignment may throw std::runtime_error when the leased text is malformed.

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#include <iostream>
#include <initializer_list>
#include <map>
#include <stdexcept>
#include <string>

// Supplied single-threaded importer resources. Buffers own their working text.
std::map<int, std::string> buffers;
std::map<std::string, std::map<std::string, std::string>> caches{{"local", {}},
                                                                 {"shared", {}}};
int serial = 0;
int currentBuffer = 0;

int takeBuffer(const std::string &source) {
    currentBuffer = ++serial;
    buffers[currentBuffer] = source;

    return currentBuffer;
}

void releaseBuffer(int lease, bool trace = false) {
    const std::string source = buffers.contains(lease) ? buffers.at(lease) : "";

    if (buffers.erase(lease) == 0) {
        if (trace)
            std::cout << "invalid buffer release\n";
        return;
    }

    if (trace)
        std::cout << "buffer released from " << source << '\n';
}

// Supplied work: parse leased text, store its fields and read the destination value.

std::string storeAssignment() {
    auto buffer = buffers.find(currentBuffer);

    if (buffer == buffers.end())
        throw std::runtime_error("no scratch lease");
    const std::string &text = buffer->second;
    auto split = text.find('=');

    if (split == std::string::npos || split == 0 || split + 1 == text.size() ||
        text.find('=', split + 1) != std::string::npos) {
        throw std::runtime_error("invalid assignment");
    }

    auto key = text.substr(0, split);
    auto value = text.substr(split + 1);
    auto &cache = caches.at("local");
    cache[key] = value;

    return key + "=" + cache.at(key);
}

void importOne(const std::string &source) {
    int lease = takeBuffer(source);

    std::cout << storeAssignment() << " stored\n";
    releaseBuffer(lease);
}

int main() {
    for (const std::string source : {"port=8080", "badline"}) {
        try {
            importOne(source);
        } catch (const std::exception &error) {
            std::cout << source << ": " << error.what() << '\n';
        }
    }

    std::cout << "leased " << buffers.size() << '\n';
}
What does the last line print?
C++ · terminal.sh
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
clang++ -std=c++2c -Wall -Wextra -pedantic main.cpp -o main && ./main

Use a fresh directory and replace main for each probe. For TypeScript, set package.json’s type field to commonjs while preserving other fields, use the installed TypeScript and Node types, and run the guarded emit command. The Go and Rust commands use one supplied main file. The importer is synchronous; its releases complete normally. Process termination, concurrent use and failures inside cleanup are outside these probes.

02On normal exits

Arrange a release that runs as the operation leaves

The next version ties release to leaving the import operation. The malformed entry still needs its failure report; trace which output happens first.

A BufferLease owner releases its buffer in its destructor.

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#include <iostream>
#include <initializer_list>
#include <map>
#include <stdexcept>
#include <string>

// Supplied single-threaded importer resources. Buffers own their working text.
std::map<int, std::string> buffers;
std::map<std::string, std::map<std::string, std::string>> caches{{"local", {}},
                                                                 {"shared", {}}};
int serial = 0;
int currentBuffer = 0;

int takeBuffer(const std::string &source) {
    currentBuffer = ++serial;
    buffers[currentBuffer] = source;

    return currentBuffer;
}

void releaseBuffer(int lease, bool trace = false) {
    const std::string source = buffers.contains(lease) ? buffers.at(lease) : "";

    if (buffers.erase(lease) == 0) {
        if (trace)
            std::cout << "invalid buffer release\n";
        return;
    }

    if (trace)
        std::cout << "buffer released from " << source << '\n';
}

// Supplied work: parse leased text, store its fields and read the destination value.

std::string storeAssignment() {
    auto buffer = buffers.find(currentBuffer);

    if (buffer == buffers.end())
        throw std::runtime_error("no scratch lease");
    const std::string &text = buffer->second;
    auto split = text.find('=');

    if (split == std::string::npos || split == 0 || split + 1 == text.size() ||
        text.find('=', split + 1) != std::string::npos) {
        throw std::runtime_error("invalid assignment");
    }

    auto key = text.substr(0, split);
    auto value = text.substr(split + 1);
    auto &cache = caches.at("local");
    cache[key] = value;

    return key + "=" + cache.at(key);
}

// Supplied resource owners; no manual allocation is required.

struct BufferLease {
    int id;
    bool trace;
    explicit BufferLease(const std::string &source, bool trace = false)
        : id(takeBuffer(source)), trace(trace) {}
    ~BufferLease() {
        releaseBuffer(id, trace);
    }
};

void importOne(const std::string &source) {
    BufferLease buffer(source, true);

    std::cout << storeAssignment() << " stored\n";
}

int main() {
    for (const std::string source : {"port=8080", "badline"}) {
        try {
            importOne(source);
        } catch (const std::exception &error) {
            std::cout << source << ": " << error.what() << '\n';
        }
    }

    std::cout << "leased " << buffers.size() << '\n';
}
Which order does the malformed input produce?
Loading The chair comes back before the failure leaves…

03Cleanup scope

Cleanup can run too early, too late or hide the failure

The same release mechanism can end at the wrong boundary or change the report. Inspect each proposed use before applying it to a batch.

The owner is an unnamed temporary expression.

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#include <iostream>
#include <initializer_list>
#include <map>
#include <stdexcept>
#include <string>

// Supplied single-threaded importer resources. Buffers own their working text.
std::map<int, std::string> buffers;
std::map<std::string, std::map<std::string, std::string>> caches{{"local", {}},
                                                                 {"shared", {}}};
int serial = 0;
int currentBuffer = 0;

int takeBuffer(const std::string &source) {
    currentBuffer = ++serial;
    buffers[currentBuffer] = source;

    return currentBuffer;
}

void releaseBuffer(int lease, bool trace = false) {
    const std::string source = buffers.contains(lease) ? buffers.at(lease) : "";

    if (buffers.erase(lease) == 0) {
        if (trace)
            std::cout << "invalid buffer release\n";
        return;
    }

    if (trace)
        std::cout << "buffer released from " << source << '\n';
}

// Supplied work: parse leased text, store its fields and read the destination value.

std::string storeAssignment() {
    auto buffer = buffers.find(currentBuffer);

    if (buffer == buffers.end())
        throw std::runtime_error("no scratch lease");
    const std::string &text = buffer->second;
    auto split = text.find('=');

    if (split == std::string::npos || split == 0 || split + 1 == text.size() ||
        text.find('=', split + 1) != std::string::npos) {
        throw std::runtime_error("invalid assignment");
    }

    auto key = text.substr(0, split);
    auto value = text.substr(split + 1);
    auto &cache = caches.at("local");
    cache[key] = value;

    return key + "=" + cache.at(key);
}

// Supplied resource owners; no manual allocation is required.

struct BufferLease {
    int id;
    bool trace;
    explicit BufferLease(const std::string &source, bool trace = false)
        : id(takeBuffer(source)), trace(trace) {}
    ~BufferLease() {
        releaseBuffer(id, trace);
    }
};

void importOne(const std::string &source) {
    BufferLease{source};

    std::cout << storeAssignment() << " stored\n";
}

int main() {
    for (const std::string source : {"port=8080", "workers=4"}) {
        try {
            importOne(source);
        } catch (const std::exception &error) {
            std::cout << source << ": " << error.what() << '\n';
        }
    }

    std::cout << "leased " << buffers.size() << '\n';
}
What does the program report?

04Repair the configuration importer

Release a buffer, release acquired resources in order, then scope every record

Repair the synchronous importer in three focused files. Protect one scratch lease, then handle partial acquisition of a destination lock. The batch must give every record its own resource lifetime and still reach records after a failed decode.

The pool owns the decoder’s working text. The supplied store function checks that the lease and any required lock are held, then returns a cache readback.

Repair the configuration importer

Protect a single operation, account for acquired resources, then preserve cleanup and progress across a batch.

  1. easy · F-CLEAN-V4-1 Protect one import lease
  2. medium · F-CLEAN-V4-2 Import under a destination lock
  3. hard · F-CLEAN-V4-3 Scope each batch record
Sources

Report a problem in this lesson

For typos, mistakes and things that don’t work. We read every report and fix what’s wrong, but we don’t reply here, so a question won’t get an answer.