Reference

Programming languages

Choose TypeScript, Go, Rust or C++ and find syntax, everyday APIs, standard libraries and tools in one place.

Scope and conventions

TypeScript/Node, Go 1.23+, Rust 2024 and C++23: from a first CLI to files, JSON, HTTP, concurrency and testing. Complete programs are labeled; other examples identify their surrounding code/imports. Optional libraries and version requirements are named in each entry.

Errors & cleanup

Recognize results and ignored values

C++

Error reporting depends on the API: from_chars returns ec and ptr; streams have state flags. (void)value explicitly discards a value. A cast converts a type, not a validity check.

Fragment

Header context plus conversion fragment.

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

std::string text = "24";
int n = 0;
auto result = std::from_chars(
    text.data(), text.data() + text.size(), n);

Return or propagate a failure

C++

A throw propagates an exception to a matching catch. Return values, error_code and expected are alternative API designs, not automatic equivalents of exceptions. Stack unwinding destroys constructed automatic objects along the unwound path.

Fragment

Fragment: imports and type/function declarations at file scope; usage statements inside a function.

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

int requirePositive(int n) {
    if (n <= 0) {
        throw std::runtime_error("positive value required");
    }
    return n;
}

Recognize resource cleanup

C++

RAII ties resource release to an owning object’s destructor. Automatic objects are destroyed at normal scope exit and during ordinary exception unwinding. This differs from garbage collection and from a manually paired allocation/free.

Fragment

Fragment: imports and type/function declarations at file scope; usage statements inside a function.

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#include <fstream>

{
    std::ifstream input("notes.txt");
    // The stream is destroyed at this block's end.
}

Choose an error-handling strategy: exceptions, error values, Result, error codes, optional, panics

C++

C++ supports every strategy, which is why codebases differ. Exceptions are the language default: the standard library throws (std::stoi, vector::at, allocation failure), destructors clean up during unwinding, and failure is invisible in signatures except for noexcept. Error codes come from C (errno, return values) and from <system_error> (std::error_code, std::errc); std::from_chars and the error_code overloads in std::filesystem report failure without throwing. C++23 adds std::expected<T, E>, a value-or-error type. std::optional represents absence. assert and std::terminate handle bugs.

Complete program

Complete program.

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#include <cassert>
#include <charconv>
#include <expected>
#include <filesystem>
#include <map>
#include <optional>
#include <print>
#include <stdexcept>
#include <string>
#include <string_view>
#include <system_error>

// 1. Exceptions (the standard library's default): std::stoi throws on bad input.
int parse_port_or_throw(const std::string& text) {
    int port = std::stoi(text); // throws invalid_argument or out_of_range
    if (port < 1 || port > 65535) throw std::out_of_range("port out of range: " + text);
    return port;
}

// 2. Error codes: std::from_chars reports std::errc and never throws or allocates.
// 3. std::expected (C++23) wraps that code in a value-or-error return type.
std::expected<int, std::errc> parse_port(std::string_view text) {
    int port = 0;
    auto [end, ec] = std::from_chars(text.data(), text.data() + text.size(), port);
    if (ec != std::errc{}) return std::unexpected(ec);
    if (end != text.data() + text.size()) return std::unexpected(std::errc::invalid_argument);
    if (port < 1 || port > 65535) return std::unexpected(std::errc::result_out_of_range);
    return port;
}

// 4. std::optional for absence, which is not a failure.
std::optional<int> lookup_port(const std::string& name) {
    static const std::map<std::string, int> well_known{{"http", 80}, {"https", 443}};
    if (auto it = well_known.find(name); it != well_known.end()) return it->second;
    return std::nullopt;
}

int main() {
    try {
        parse_port_or_throw("99999");
    } catch (const std::out_of_range& e) {
        std::println("caught: {}", e.what());
    }

    for (std::string_view text : {"8080", "eighty"}) {
        if (auto port = parse_port(text)) {
            std::println("parsed: {}", *port);
        } else {
            std::println("error: {}", std::make_error_code(port.error()).message());
        }
    }

    // Many std::filesystem functions have a throwing overload and an error_code overload.
    std::error_code ec;
    auto size = std::filesystem::file_size("/no/such/file", ec); // uintmax_t(-1) on error
    if (ec) std::println("file_size failed: {}", ec.message());
    else std::println("file size: {}", size);

    std::println("ssh port: {}", lookup_port("ssh").value_or(-1));

    // 5. assert for bugs: aborts in debug builds, compiled out with -DNDEBUG.
    auto https = lookup_port("https");
    assert(https.has_value() && "https is always in the table");
    std::println("https port: {}", *https);
}

Trade-offs: exceptions keep the happy path clean and cost nothing until thrown, but a throw is slow and some projects compile with -fno-exceptions. Error codes and expected are explicit and predictable, but must be checked and propagated by hand.

In practice: follow the codebase. In new code, throw for rare, environmental failures and use std::expected for expected outcomes on hot or exception-free paths. Use optional for absence, never for errors that need a reason. Catch by const reference.

std::stoi throws std::invalid_argument or std::out_of_range, and accepts trailing garbage ("80abc" gives 80). std::from_chars never throws and also stops at the first character it cannot use ("80abc" gives 80 with ptr at 'a'), so check ptr against the end to reject trailing text.

With -fno-exceptions (common in games and embedded code) a throw is a compile error or an abort, depending on the toolchain; error codes and std::expected are the only options there.

std::expected needs C++23 and a recent standard library: libstdc++ 12, libc++ 16 or MSVC 19.33 or later.

Define a custom error type: Error subclasses, error structs, error enums, exception hierarchies

C++

Exception types derive, directly or through a base, from std::exception, usually from std::runtime_error or std::logic_error so what() returns the message. Add members for the data a handler needs and catch the most derived type first, by const reference. A catch for the base type handles every leaf that has no handler of its own.

Complete program

Complete program.

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

// An exception hierarchy: derive from std::runtime_error so what() carries the message.
class AppError : public std::runtime_error {
public:
    using std::runtime_error::runtime_error;
};

class NotFoundError : public AppError {
public:
    explicit NotFoundError(std::string id)
        : AppError("order " + id + " not found"), id_(std::move(id)) {}
    const std::string& id() const noexcept { return id_; }

private:
    std::string id_;
};

class ValidationError : public AppError {
public:
    ValidationError(std::string field, const std::string& reason)
        : AppError("invalid " + field + ": " + reason), field_(std::move(field)) {}
    const std::string& field() const noexcept { return field_; }

private:
    std::string field_;
};

void reserve(const std::string& id, int quantity) {
    if (id != "o1") throw NotFoundError(id);
    if (quantity < 1) throw ValidationError("quantity", std::to_string(quantity) + " is below 1");
    if (quantity > 5) throw AppError("only 5 in stock");
}

int main() {
    for (auto [id, qty] : {std::pair{"o1", 2}, {"o9", 1}, {"o1", 0}, {"o1", 8}}) {
        try {
            reserve(id, qty);
            std::println("reserved {} x{}", id, qty);
        } catch (const NotFoundError& e) { // most derived first, always by const reference
            std::println("404 id={}: {}", e.id(), e.what());
        } catch (const ValidationError& e) {
            std::println("422 field={}: {}", e.field(), e.what());
        } catch (const AppError& e) { // the base catches every other application error
            std::println("409: {}", e.what());
        }
    }
}

In practice: a shallow hierarchy (one application base, a few leaf types) is enough. Catch by const& to avoid slicing, rethrow with plain throw; to keep the original type. For error codes rather than exceptions, <system_error> lets a library define its own std::error_category (see the notes).

Catching by value (catch (AppError e)) copies and slices a derived exception down to the base type. Always catch by const reference.

Custom error codes: define an enum class, a std::error_category subclass whose name() and message(int) describe it, a make_error_code(YourEnum) overload found by argument-dependent lookup, and a std::is_error_code_enum specialization. The enum then converts to std::error_code and can be thrown inside std::system_error. Use this when a library reports codes from its own domain (a database, a protocol).

The category object must be a singleton, because error_code equality compares category addresses: return a reference to one function-local static instance. Override default_error_condition if your codes should compare equal to portable std::errc values.

Add context to an error: cause, %w, source chains, nested exceptions

C++

std::throw_with_nested(e), called inside a catch block, throws an object that derives from both your exception type and std::nested_exception, and the nested part captures the exception currently being handled. std::rethrow_if_nested(e) rethrows that stored cause if there is one, so a recursive function can print or search the chain. For error codes, wrap a std::error_code in std::system_error with a context string, and std::filesystem::filesystem_error does the same with the paths involved.

Complete program

Complete program.

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#include <exception>
#include <filesystem>
#include <fstream>
#include <print>
#include <stdexcept>
#include <string>
#include <system_error>

std::string read_settings(const std::filesystem::path& path) {
    // file_size throws std::filesystem::filesystem_error, derived from std::system_error.
    std::string text(std::filesystem::file_size(path), '\0');
    std::ifstream(path, std::ios::binary).read(text.data(), static_cast<std::streamsize>(text.size()));
    return text;
}

std::string load_config() {
    try {
        return read_settings("/no/such/dir/settings.json");
    } catch (...) {
        // Throws a type derived from both runtime_error and std::nested_exception,
        // which captures the exception currently being handled as the cause.
        std::throw_with_nested(std::runtime_error("load config"));
    }
}

// rethrow_if_nested rethrows the stored cause if e has one; recurse to print the chain.
void print_chain(const std::exception& e, int depth = 0) {
    std::println("{}{}", depth == 0 ? "" : "  caused by: ", e.what());
    try {
        std::rethrow_if_nested(e);
    } catch (const std::exception& cause) {
        print_chain(cause, depth + 1);
    }
}

// Search the chain for a std::system_error and return its code.
std::error_code find_code(const std::exception& e) {
    if (auto* se = dynamic_cast<const std::system_error*>(&e)) return se->code();
    try {
        std::rethrow_if_nested(e);
    } catch (const std::exception& cause) {
        return find_code(cause);
    }
    return {};
}

int main() {
    try {
        load_config();
    } catch (const std::exception& e) {
        print_chain(e);
        auto ec = find_code(e);
        std::println("root code: {} ({})", ec.value(), ec.message());
        std::println("is ENOENT: {}", ec == std::errc::no_such_file_or_directory);
    }
}

In practice: nested exceptions are the standard tool, but they are verbose and few libraries use them. Many codebases instead add context to the message and keep a code (system_error) or a cause member in their own exception type. With std::expected, add context with transform_error.

Call throw_with_nested only while an exception is being handled (inside a catch). Outside one, the stored nested pointer is null, and rethrow_if_nested on that object calls std::terminate.

rethrow_if_nested only works on polymorphic types; it uses dynamic_cast to find the std::nested_exception base.

Boost.Exception and Boost.System add arbitrary context data to exceptions and source locations to error codes.

Return typed errors: Result, (T, error), Result<T, E>, std::expected

C++

C++23's std::expected<T, E> holds either a T or an E; return std::unexpected(e) for the error case. It converts to bool, value() throws std::bad_expected_access on error, and error() reads the error. The monadic operations chain steps: and_then runs a function returning another expected, transform maps the value, or_else recovers from an error, and transform_error maps the error type. Make E an enum class and handle it with a switch; -Wall includes -Wswitch, which warns about missing enumerators. For errors with per-kind data, E can be a std::variant.

Complete program

Complete program.

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#include <algorithm>
#include <cctype>
#include <expected>
#include <print>
#include <string>
#include <string_view>

enum class UsernameError { empty, too_long, bad_char, reserved };

// -Wall enables -Wswitch, which warns when an enumerator is missing from a switch.
std::string_view message(UsernameError e) {
    switch (e) {
    case UsernameError::empty: return "enter a username";
    case UsernameError::too_long: return "use at most 16 characters";
    case UsernameError::bad_char: return "only a-z, 0-9 and _ are allowed";
    case UsernameError::reserved: return "that name is reserved";
    }
    return "unknown"; // unreachable for valid enumerators
}

std::expected<std::string, UsernameError> parse_username(std::string_view input) {
    auto first = input.find_first_not_of(' ');
    if (first == std::string_view::npos) return std::unexpected(UsernameError::empty);
    std::string name(input.substr(first, input.find_last_not_of(' ') - first + 1));
    if (name.size() > 16) return std::unexpected(UsernameError::too_long);
    std::ranges::transform(name, name.begin(), [](unsigned char c) { return std::tolower(c); });
    auto allowed = [](unsigned char c) { return std::isalnum(c) || c == '_'; };
    bool valid = std::ranges::all_of(name, allowed);
    if (!valid) return std::unexpected(UsernameError::bad_char);
    return name;
}

std::expected<std::string, UsernameError> not_reserved(std::string name) {
    if (name == "admin" || name == "root") return std::unexpected(UsernameError::reserved);
    return name;
}

int main() {
    for (std::string_view input : {"  Ada_L ", "", "grace hopper", "xxxxxxxxxxxxxxxxxxxx", "Admin"}) {
        // and_then chains a step returning expected; transform maps the value.
        auto r = parse_username(input).and_then(not_reserved).transform([](const std::string& n) {
            return n.size();
        });
        if (r) {
            std::println("\"{}\" -> ok, {} chars", input, *r);
        } else {
            std::println("\"{}\" -> error: {}", input, message(r.error()));
        }
    }

    // or_else recovers from an error; transform_error maps it to another type.
    auto guest = parse_username("!").or_else([](UsernameError) {
        return std::expected<std::string, UsernameError>("guest");
    });
    std::println("fallback: {}", *guest);

    auto text = parse_username("root!").transform_error([](UsernameError e) {
        return std::string(message(e));
    });
    std::println("as text: {}", text.error_or("none"));
}

In practice: use expected for expected failures in code that avoids exceptions or sits on a hot path, and keep E small and cheap to copy. Do not call value() as a shortcut; check first or use the monadic operations.

std::expected needs C++23, and the monadic operations (and_then, transform, or_else, transform_error) need libstdc++ 13, libc++ 17 or MSVC 19.36 or later. tl::expected (header-only) and Boost.Outcome provide the same shape for C++17.

*r and r->x on an expected holding an error are undefined behavior, like an empty optional. value() checks and throws.

and_then and or_else require the continuation to return an expected with the same error type (or value type, for or_else); use transform_error first if they differ.

Crash on a bug (panic): uncaught exceptions, panic/recover, panic!, std::terminate

C++

std::terminate is the unrecoverable path: it runs the terminate handler, which calls std::abort by default. It is called when an exception escapes a noexcept function (destructors are noexcept by default), when an exception is not caught at all, or when a second exception is thrown during unwinding. assert(cond) calls std::abort when the condition is false, and disappears completely when NDEBUG is defined. std::set_terminate installs a last-chance handler that may log, but it must end the process. Contracts (pre, post, contract_assert) are part of C++26, not C++23, and compilers are still adding support.

Complete program

Complete program. It ends on purpose through std::terminate, with exit status 3.

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#include <cassert>
#include <cstdio>
#include <cstdlib>
#include <exception>
#include <print>
#include <stdexcept>
#include <string>

int apply_discount(int cents, int percent) {
    // assert aborts on a broken invariant in debug builds; -DNDEBUG removes it.
    assert(percent >= 0 && percent <= 100 && "percent out of range");
    return cents * (100 - percent) / 100;
}

// A recoverable failure: the caller can catch it and carry on.
int parse_port(const std::string& text) {
    int port = std::stoi(text);
    if (port < 1 || port > 65535) throw std::out_of_range("port out of range");
    return port;
}

void write_to_disk(bool disk_ok) {
    if (!disk_ok) throw std::runtime_error("audit disk failed");
}

// noexcept is a promise. If an exception escapes, std::terminate is called:
// no unwinding to the caller, and no catch can intervene.
void flush_audit_log(bool disk_ok) noexcept {
    write_to_disk(disk_ok);
    std::println("audit log flushed");
}

int main() {
    std::println("discounted: {}", apply_discount(1000, 15));

    try {
        parse_port("99999");
    } catch (const std::exception& e) {
        std::println("recovered: {}", e.what());
    }

    static_assert(noexcept(flush_audit_log(true)), "noexcept is part of the type contract");

    // A terminate handler is the last place to log; it must end the process.
    std::set_terminate([] {
        std::println("fatal: std::terminate called, exiting with status 3");
        std::fflush(stdout); // _Exit skips flushing and destructors
        std::_Exit(3);
    });

    flush_audit_log(true);
    flush_audit_log(false); // ends the program through std::terminate
    std::println("never printed");
}

In practice: throw or return std::expected for recoverable errors; use assert for internal invariants that tests should catch; mark functions noexcept only when they truly cannot fail (moves, swaps, destructors), because a throw inside one terminates. For a check that must stay in release builds, write an explicit if plus std::abort or a throw.

Whether the stack is unwound before std::terminate runs for an uncaught exception is implementation-defined; do not rely on destructors running.

std::_Exit and std::abort skip flushing stdio buffers and running destructors; flush what you need first, as the handler here does.

Release builds usually define NDEBUG, so assert(f()) loses the call f() as well as the check. Never put side effects inside assert.

Collect several errors: AggregateError, errors.Join, partition, a vector of errors

C++

The standard library has no aggregate error type. With std::expected, keep one result per item and split them into values and errors afterwards. With exceptions, catch per item and store std::current_exception() in a std::vector<std::exception_ptr>; std::rethrow_exception later rethrows each one so it can be inspected. To throw a combined failure, define an exception type that holds the list.

Complete program

Complete program.

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#include <charconv>
#include <exception>
#include <expected>
#include <print>
#include <stdexcept>
#include <string>
#include <string_view>
#include <utility>
#include <vector>

struct LineError {
    std::size_t line;
    std::string message;
};

std::expected<int, LineError> parse_line(std::size_t line, std::string_view text) {
    int value = 0;
    auto [end, ec] = std::from_chars(text.data(), text.data() + text.size(), value);
    if (ec != std::errc{} || end != text.data() + text.size())
        return std::unexpected(LineError{line, "not an integer: \"" + std::string(text) + "\""});
    if (value < 0) return std::unexpected(LineError{line, "negative: " + std::string(text)});
    return value;
}

int main() {
    std::vector<std::string_view> input{"12", "x", "30", "-4", "7"};

    // One std::expected per item keeps every outcome; split them afterwards.
    std::vector<int> values;
    std::vector<LineError> errors;
    for (std::size_t i = 0; i < input.size(); ++i) {
        if (auto r = parse_line(i + 1, input[i])) values.push_back(*r);
        else errors.push_back(std::move(r.error()));
    }

    std::println("parsed {}", values);
    for (const auto& e : errors) std::println("  line {}: {}", e.line, e.message);

    // With exceptions, catch per item and keep the std::exception_ptr for later.
    std::vector<std::exception_ptr> failures;
    for (std::string_view text : input) {
        try {
            if (std::stoi(std::string(text)) < 0) throw std::domain_error("negative");
        } catch (...) {
            failures.push_back(std::current_exception());
        }
    }
    std::println("{} of {} items threw", failures.size(), input.size());
    for (const auto& p : failures) {
        try {
            std::rethrow_exception(p);
        } catch (const std::exception& e) {
            std::println("  {}", e.what());
        }
    }
}

In practice: for validation, collect plain error structs (field, message) in a vector and return them; for batches, return std::vector<std::expected<T, E>> or a struct of successes and failures. An exception_ptr keeps the exception object alive and can move it across threads, which is how std::future reports a task's failure.

Printing containers with std::println needs C++23 range formatting: GCC 15+ (libstdc++) or libc++ 17+. With older libraries, print the elements in a loop.

An exception_ptr extends the lifetime of the exception object; storing many of them keeps every exception and its message alive.

Decide where to handle an error: translate at boundaries, log once, retry with backoff

C++

With exceptions, the boundaries are the catch blocks: code in between does not mention errors at all, and RAII cleans up as they pass. Put a catch at a module boundary to translate a low-level exception into a domain one (std::throw_with_nested keeps the cause), next to a call to retry transient failures with backoff, and at the top (a request handler, main) to choose the response and log. Plain throw; rethrows the original object unchanged when a handler decides it cannot help.

Complete program

Complete program.

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#include <algorithm>
#include <chrono>
#include <exception>
#include <print>
#include <random>
#include <stdexcept>
#include <string>
#include <thread>
#include <utility>

// --- storage layer -----------------------------------------------------------
struct DbError : std::runtime_error {
    enum class Code { connection_reset, unique_violation };
    Code code;
    DbError(Code c, const std::string& what) : std::runtime_error(what), code(c) {}
    bool transient() const noexcept { return code == Code::connection_reset; }
};

int insert_user(const std::string& email) {
    static int calls = 0;
    using enum DbError::Code;
    if (++calls == 1 || email == "down@example.com") {
        throw DbError(connection_reset, "socket closed by peer");
    }
    if (email == "ada@example.com") throw DbError(unique_violation, "duplicate key users_email_key");
    return 42;
}

// --- service layer: translate the failures callers act on; keep the cause -----
struct EmailTaken : std::runtime_error {
    using std::runtime_error::runtime_error;
};

// Capped exponential backoff with full jitter: before retry i, sleep a random
// time in [0, min(200ms, 10ms * 2^i)).
template <class F>
auto with_retry(int attempts, F f) {
    static std::mt19937 rng{std::random_device{}()};
    for (int i = 1;; ++i) {
        try {
            return f();
        } catch (const DbError& e) {
            if (!e.transient() || i == attempts) throw; // rethrow permanent failures as-is
        }
        int ceiling_ms = std::min(200, 10 << i);
        std::this_thread::sleep_for(
            std::chrono::milliseconds(std::uniform_int_distribution(0, ceiling_ms - 1)(rng)));
    }
}

int register_user(const std::string& email) {
    try {
        return with_retry(3, [&] { return insert_user(email); });
    } catch (const DbError& e) {
        if (e.code == DbError::Code::unique_violation) {
            std::throw_with_nested(EmailTaken("email already registered: " + email));
        }
        throw;
    }
}

// --- handler: picks the status and message, and is the only place that logs ---
std::pair<int, std::string> handle_signup(const std::string& email) {
    try {
        return {201, "user " + std::to_string(register_user(email)) + " created"};
    } catch (const EmailTaken&) {
        return {409, "That email is already registered."}; // expected: no log
    } catch (const std::exception& e) {
        std::println(stderr, "[req-7f3a] signup failed: {}", e.what());
        return {500, "Something went wrong (reference req-7f3a)."};
    }
}

int main() {
    auto [s1, b1] = handle_signup("grace@example.com"); // first attempt is retried
    std::println("{} {}", s1, b1);
    auto [s2, b2] = handle_signup("ada@example.com");
    std::println("{} {}", s2, b2);
    auto [s3, b3] = handle_signup("down@example.com"); // transient every time: gives up
    std::println("{} {}", s3, b3);
}

In practice: catch as little as possible, as late as possible, and always by const reference. Never let exceptions escape destructors, threads, or C callbacks; catch at those edges. At the top, catch std::exception for logging and give users a generic message; do not show what() if it may contain internal details.

An exception escaping a std::thread function calls std::terminate; catch inside the thread, or use std::async/std::future, which carry the exception to get().

Full jitter (a random wait between 0 and the current ceiling) stops many clients that failed together from retrying together. Bound the whole operation by a deadline as well as an attempt count.

using enum (C++20) brings enumerators into scope, which keeps the DbError(connection_reset, ...) calls short.