Cheat Sheet - Linux: /linux/ - CLI: /linux/cli/ - locate vs type vs which vs whereis: /linux/cli/locate-vs-type-vs-which-vs-whereis/ - make: /linux/cli/make/ - awk: /linux/cli/awk/ - find: /linux/cli/find/ - grep: /linux/cli/grep/ - pgrep: /linux/cli/pgrep/ - ps: /linux/cli/ps/ - pstree: /linux/cli/pstree/ - trap: /linux/cli/trap/ - xargs: /linux/cli/xargs/ - Shell: /linux/shell/ - BASH_SOURCE: /linux/shell/bash-source/ - Redirection: /linux/shell/redirection/ - Special Variables: /linux/shell/special-variables/ - Scripting Tips: /linux/shell/script-tips/ - set -o vi: /linux/shell/bash-vi-mode/ - Shell Processing Order: /linux/shell/process-order/ - What are Interactive and Login Shells?: /linux/shell/interactive-login/ - Double Quote Expansion: /linux/shell/shell-expansion/ - System Programming: /linux/system-programming/ - File I/O: /linux/system-programming/file-io/ - Process: /linux/system-programming/process/ - Shared Libraries: /linux/system-programming/shared-libraries/ - Kernel: /linux/kernel/ - Go: /programming/go/ - Concurrency: /programming/go/concurrency/ - CSP (Communicating Sequential Processes) and Channels: /programming/go/concurrency/csp/ - Channel: /programming/go/concurrency/channel/ - Select: /programming/go/concurrency/select/ - sync: /programming/go/concurrency/sync/ - Concurrency Patterns: /programming/go/concurrency/patterns/ - Goroutines and the Go Runtime: /programming/go/concurrency/runtime/ - Standard Library: /programming/go/std/ - os: /programming/go/std/os/ - context: /programming/go/std/context/ - io: /programming/go/std/io/ - json: /programming/go/std/json/ - net/http: /programming/go/std/net-http/ - slog: /programming/go/std/slog/ - testing: /programming/go/std/testing/ - time: /programming/go/std/time/ - Ellipsis (...): /programming/go/ellipsis/ - error: /programming/go/error/ - Function: /programming/go/function/ - Go Tool: /programming/go/tool/ - Interface: /programming/go/interface/ - Map: /programming/go/map/ - Package and Module: /programming/go/package-module/ - Pointer: /programming/go/pointer/ - Slice: /programming/go/slice/ - String: /programming/go/string/ - Switch: /programming/go/switch/ - Comparison: /programming/go/comparison/ - defaultdict: /programming/python/collections/defaultdict/ - heapq: /programming/python/collections/heapq/ - @cache: /programming/python/cache/ - abc: /programming/python/abc/ - bisect: /programming/python/bisect/ - Type Hints: /programming/python/type-hints/ - Passing Mechanism: /programming/python/passing-mechanism/ - uv: /programming/python/uv/ - *args and **kwargs: /programming/python/args-kwargs/ - re: /programming/python/re/ - C: /programming/c/ - Pointers and Arrays: /programming/c/pointer/ - Syntax Basics: /programming/c/syntax-basics/ - static: /programming/c/static/ - Bit Manipulation: /programming/c/bit-manipulation/ - C vs C++: /programming/c/c-vs-cpp/ - stdatomic: /programming/c/stdatomic/ - C++: /programming/cpp/ - RAII (Resource Acquisition Is Initialization): /programming/cpp/raii/ - Copy Elision & Move Semantics: /programming/cpp/copy-elision-and-move-semantics/ - Most Vexing Parse & In-Class Initializer: /programming/cpp/most-vexing-parse/ - C++ Keywords Reference: /programming/cpp/keywords/ - C++ Primer: /programming/cpp/primer/ - Variables and Basic Types: /programming/cpp/primer/variables-and-basic-types/ - Expressions: /programming/cpp/primer/expressions/ - Type Conversions and Casts: /programming/cpp/primer/type-conversions-and-casts/ - Statements: /programming/cpp/primer/statements/ - Functions: /programming/cpp/primer/functions/ - Classes: /programming/cpp/primer/classes/ - The IO Library: /programming/cpp/primer/io-library/ - STL: /programming/cpp/primer/stl/ - Lambda Expressions: /programming/cpp/primer/lambda/ - Smart Pointers: /programming/cpp/primer/smart-pointers/ - Copy Control: /programming/cpp/primer/copy-control/ - Overloaded Operations and Conversions: /programming/cpp/primer/operator-overloading/ - Object-Oriented Programming (OOP): /programming/cpp/primer/oop/ - Templates and Generic Programming: /programming/cpp/primer/templates/ - Namespaces: /programming/cpp/primer/namespaces/ - Pointers to Class Member: /programming/cpp/primer/pointers-to-class-member/ - Advanced: /programming/cpp/advanced/ - Error Handling: /programming/cpp/advanced/error-handling/ - Concurrency & Threading: /programming/cpp/advanced/concurrency/ - Unit Testing: /programming/cpp/advanced/unit-testing/ - Comparison: /programming/comparison/ - Kubernetes: /cloud-devops/kubernetes/ - Fleet: /cloud-devops/kubernetes/gke/fleet/ - Kustomize vs Helm: /cloud-devops/kubernetes/kustomize-vs-helm/ - API Extension: /cloud-devops/kubernetes/api-extension/ - Concept: /cloud-devops/kubernetes/kueue/concept/ - DRA: /cloud-devops/kubernetes/dra/ - Secret Manager: /cloud-devops/terraform/google-secret-manager/ - Knowledge: /network/knowledge/ - PDU: /network/knowledge/osi-model/ - curl: /network/cli/curl/ - Concurrency Concepts: /cs/concurrency-and-parallelism/concepts/ - Concurrency vs Parallelism: /cs/concurrency-and-parallelism/concurrency-vs-parallelism/ - Mutex vs Atomic: /cs/concurrency-and-parallelism/mutex-vs-atomic/ - Regular Expression: /cs/regular-expression/ - Multiplexer vs Dispatcher: /cs/multiplexer-vs-dispatcher/ - Driver and Runtime: /ai-ml/gpu/driver-and-runtime/ - Serving: /ai-ml/serving/ - Dotfiles: /dotfiles/ - Git: /dotfiles/git/ - Cheat Sheet: /dotfiles/git/cheat-sheet/ - revisions: /dotfiles/git/revisions/ - Submodule vs Worktree: /dotfiles/git/submodule-vs-worktree/ - checkout, reset -> switch, restore: /dotfiles/git/checkout-switch-restore-reset/ - rebase: /dotfiles/git/rebase/ - Branching and Merging: /dotfiles/git/branching-merging/ - Vim: /dotfiles/vim/ - Plugin: /dotfiles/vim/plugin/ - auto-pairs: /dotfiles/vim/plugin/auto-pairs/ - vim-commentary: /dotfiles/vim/plugin/vim-commentary/ - vim-easymotion: /dotfiles/vim/plugin/vim-easymotion/ - vim-surround: /dotfiles/vim/plugin/vim-surround/ - Marks: /dotfiles/vim/tips/marks/ - vimrc: /dotfiles/vim/vimrc/ - lf: /dotfiles/lf/ # Error Handling in C++: Abseil `Status`, `StatusOr` & Go/Rust Comparison This article explains why large-scale C++ codebases favor **value-based error handling (Errors as Values)** over C++ exceptions (`try-catch`), how to use open-source **Abseil (`abseil-cpp`)** types `absl::Status` and `absl::StatusOr`, and how this design maps directly to **Go's `(T, error)`**, **Rust's `Result`**, and **C++23's `std::expected`**. --- ## 1. Why Large-Scale C++ Projects Avoid Exceptions (`try-catch`) Although standard C++ supports `throw` and `try-catch`, many large production C++ codebases (following the [Google C++ Style Guide](https://google.github.io/styleguide/cppguide.html#Exceptions)) disable exceptions via `-fno-exceptions` and rely on **explicit error return values**. ### Three Practical Limitations of C++ Exceptions 1. **Invisible Control Flow at the Callsite:** - Looking at `int x = Compute(a) + Fetch(b);`, it is impossible to tell from the callsite whether either function might throw an exception and abruptly unwind the call stack. - Because failure paths are not part of the function's return type signature, reasoning about control flow during code reviews and refactoring becomes significantly harder. 2. **Fragile Exception Safety Across Large Codebases:** - Unless every intermediate frame strictly adheres to [RAII]({{< relref "/programming/cpp/raii.md" >}}) and strong exception safety guarantees, stack unwinding can leave objects with broken invariants or leaked resources. - Integrating exception-throwing code with legacy or third-party C++ libraries not written with exception safety in mind frequently leads to subtle bugs. 3. **Unwinding Overhead and Binary Size Cost:** - While "zero-cost exceptions" optimize the non-throwing happy path, actually throwing an exception incurs thousands of CPU cycles traversing unwind tables (`.eh_frame`) and RTTI metadata, inflating both binary size and tail latency when errors occur. > **The Alternative: Errors as Values:** > Instead of jumping up the call stack via `throw`, functions that can fail encode that possibility directly in their **return type**, forcing the caller to inspect and handle errors explicitly with compiler enforcement. --- ## 2. `absl::Status`: Representing Success or Error State When a function does not return a data payload and only needs to report **whether an operation succeeded or why it failed** (replacing `bool` or raw `int` error codes), it returns [`absl::Status`](https://abseil.io/docs/cpp/guides/status) from open-source Abseil. - **Header:** `#include "absl/status/status.h"` - **Representation:** - **On success (`OK`):** Represented as a single zero integer inlined without any heap allocation (effectively zero overhead). - **On failure:** Holds a canonical `absl::StatusCode` (aligned 1:1 with standard gRPC status codes), a human-readable error message, and optional structured payloads. - **`[[nodiscard]]` Enforcement:** `absl::Status` is annotated with `[[nodiscard]]`, so ignoring a returned `Status` triggers a **compiler warning or error**. ### Canonical `absl::StatusCode` Factory Functions | Factory Function (`absl/status/status.h`) | Corresponding `absl::StatusCode` | Typical Use Case | | :--- | :--- | :--- | | **`absl::OkStatus()`** | `StatusCode::kOk` (`0`) | Operation completed **successfully** | | **`absl::InvalidArgumentError(msg)`** | `StatusCode::kInvalidArgument` | Caller supplied an invalid argument (e.g., negative age, empty string) | | **`absl::NotFoundError(msg)`** | `StatusCode::kNotFound` | Requested file, key, or database record does not exist | | **`absl::AlreadyExistsError(msg)`** | `StatusCode::kAlreadyExists` | Resource or key being created already exists | | **`absl::PermissionDeniedError(msg)`** | `StatusCode::kPermissionDenied` | Caller lacks authorization for the operation | | **`absl::UnavailableError(msg)`** | `StatusCode::kUnavailable` | Transient network or service failure (often retryable) | | **`absl::InternalError(msg)`** | `StatusCode::kInternal` | Broken internal system invariant or unexpected bug | ### Basic Usage of `absl::Status` ```cpp #include #include "absl/status/status.h" #include "absl/strings/string_view.h" absl::Status ValidateUsername(absl::string_view username) { if (username.empty()) { return absl::InvalidArgumentError("Username cannot be empty"); } if (username.size() > 32) { return absl::InvalidArgumentError("Username exceeds 32 characters"); } return absl::OkStatus(); } void HandleRegistration(absl::string_view username) { absl::Status status = ValidateUsername(username); if (!status.ok()) { std::cerr << "Validation failed [" << status.code() << "]: " << status.message() << "\n"; return; } // Proceed with registration... } ``` --- ## 3. `absl::StatusOr`: Holding Either a Value (`T`) or an Error (`Status`) When a function returns a **result value `T` on success** or an **`absl::Status` error on failure**, it returns [`absl::StatusOr`](https://abseil.io/docs/cpp/guides/status). - **Header:** `#include "absl/status/statusor.h"` - **Core Concept (Tagged Union / Sum Type):** - Holds **either** a valid value of type `T` **or** a non-OK `absl::Status` explaining why the value is absent (conceptually similar to `std::variant`). - If `ok()` is `true`, a valid `T` is guaranteed to exist; if `ok()` is `false`, a non-OK `absl::Status` is guaranteed to exist. **Ambiguous states (both present or both empty) are unrepresentable.** ### Why Prefer `absl::StatusOr` Over Output Parameters (`Status Func(T* out)`)? Historically, C++ codebases without exceptions used pointer output parameters (`absl::Status Parse(string_view in, Data* out)`) to return both a status and a value. `absl::StatusOr` eliminates the drawbacks of output parameters: | Aspect | Legacy Output Parameter (`Status Func(T* out)`) | Modern Value Return (`absl::StatusOr Func()`) | | :--- | :--- | :--- | | **Caller Initialization** | Requires default-constructing a dummy `T out;` beforehand | Works seamlessly with types that have no default constructor | | **Move-Only Types** | Awkward to return `std::unique_ptr` | Cleanly returns ownership via `absl::StatusOr>` | | **Factory Functions** | Constructors cannot return errors, forcing two-phase `Init()` | Enables `static absl::StatusOr Create(...)` so partially initialized objects never exist | | **Copy/Move Optimization** | Separates declaration from population | Integrates naturally with [Copy Elision & Move Semantics]({{< relref "/programming/cpp/copy-elision-and-move-semantics.md" >}}) | ### Using `absl::StatusOr` Safely ```cpp #include #include #include #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" struct UserProfile { int id; std::string name; }; // Returns UserProfile on success, or an error absl::Status on failure absl::StatusOr FetchUserProfile(int user_id) { if (user_id <= 0) { // Returning an absl::Status implicitly converts it into a non-OK StatusOr return absl::InvalidArgumentError("user_id must be positive"); } if (user_id == 404) { return absl::NotFoundError(absl::StrCat("User ", user_id, " not found")); } // Returning a T (UserProfile) implicitly constructs an OK StatusOr return UserProfile{.id = user_id, .name = "Alice"}; } void ProcessUser(int user_id) { absl::StatusOr result = FetchUserProfile(user_id); // 1. Always check ok() before accessing the value. if (!result.ok()) { // Extract the underlying absl::Status via result.status() absl::Status err = result.status(); return; } // 2. Once ok() is verified, dereference with * or -> (or .value()) int id = result->id; // 3. For heap-owning types (std::string, std::vector) or move-only types (std::unique_ptr), // use std::move(*result) to move the value out without copying! UserProfile profile = std::move(*result); } ``` > **Warning (Accessing the value when `!ok()`):** > Calling `*result`, `result->`, or `result.value()` when `result.ok()` is `false` terminates the process immediately (crash/abort). **Always verify `if (!result.ok())` before dereferencing.** --- ## 4. Error Propagation Macros (`RETURN_IF_ERROR` & `ASSIGN_OR_RETURN`) When propagating errors up the call stack without custom recovery logic, writing four lines of `if (!s.ok()) return s;` after every call obscures the core business logic. Across the open-source C++ ecosystem (Protobuf, TensorFlow, OpenXLA, MediaPipe, OR-Tools), two standard macro patterns, **`RETURN_IF_ERROR`** and **`ASSIGN_OR_RETURN`**, are used to keep error propagation concise. ### 1. Before vs. After Propagation Macros ```cpp // ❌ Verbose manual error propagation absl::StatusOr PlaceOrderVerbose(int user_id, int item_id) { absl::Status auth_status = VerifyAuthToken(user_id); if (!auth_status.ok()) { return auth_status; } absl::StatusOr user_or = FetchUserProfile(user_id); if (!user_or.ok()) { return user_or.status(); } UserProfile user = std::move(*user_or); absl::StatusOr item_or = CheckInventory(item_id); if (!item_or.ok()) { return item_or.status(); } InventoryItem item = std::move(*item_or); return CreateReceipt(user, item); } // ✅ Concise error propagation with RETURN_IF_ERROR and ASSIGN_OR_RETURN absl::StatusOr PlaceOrderClean(int user_id, int item_id) { RETURN_IF_ERROR(VerifyAuthToken(user_id)); ASSIGN_OR_RETURN(UserProfile user, FetchUserProfile(user_id)); ASSIGN_OR_RETURN(InventoryItem item, CheckInventory(item_id)); return CreateReceipt(user, item); } ``` ### 2. How the Macros Expand Under the Hood A portable implementation compatible with `absl/status` looks like this: ```cpp // 1. RETURN_IF_ERROR(expr): // Evaluates expr; if the resulting absl::Status is not OK, returns it from the enclosing function. #define RETURN_IF_ERROR(expr) \ do { \ if (const absl::Status _status = (expr); !_status.ok()) \ return _status; \ } while (0) // 2. ASSIGN_OR_RETURN(lhs, rexpr): // Evaluates rexpr (an absl::StatusOr); if not OK, returns its status() from the enclosing // function. Otherwise, moves the contained value into lhs. #define STATUS_MACROS_CONCAT_IMPL_(x, y) x##y #define STATUS_MACROS_CONCAT_(x, y) STATUS_MACROS_CONCAT_IMPL_(x, y) #define ASSIGN_OR_RETURN(lhs, rexpr) \ auto STATUS_MACROS_CONCAT_(_status_or_, __LINE__) = (rexpr); \ if (!STATUS_MACROS_CONCAT_(_status_or_, __LINE__).ok()) { \ return std::move(STATUS_MACROS_CONCAT_(_status_or_, __LINE__)).status(); \ } \ lhs = *std::move(STATUS_MACROS_CONCAT_(_status_or_, __LINE__)) ``` > **Why must `ASSIGN_OR_RETURN` be a macro rather than a regular C++ function?** > It must perform two actions in the **caller's frame**: (1) execute an early `return` from the enclosing function (`PlaceOrderClean`) on error, and (2) introduce a new local variable (`UserProfile user`) into the enclosing scope on success. In C++, only preprocessor macros can both inject a `return` statement into the caller and declare a variable in the caller's scope. --- ## 5. Comparing C++ (`StatusOr` / `std::expected`), Go, and Rust The **"Errors as Values"** philosophy behind `absl::StatusOr` shares the exact same conceptual foundation as **Go**, **Rust**, and **C++23's `std::expected`**. ### 1. Side-by-Side Comparison Matrix | Dimension | C++ Abseil (`absl::StatusOr`) | C++23 Standard (`std::expected`) | Go (`(T, error)`) | Rust (`Result`) | | :--- | :--- | :--- | :--- | :--- | | **Type Structure** | **Sum Type** (holds either `T` or `absl::Status`) | **Sum Type** (holds either `T` or arbitrary error type `E`) | **Product Type / Multi-Return** (zero-value of `T` and `error` coexist) | **Algebraic Data Type (`enum`)** (`Ok(T)` or `Err(E)`) | | **Status-Only Return** | `absl::Status` | `std::expected` | `error` | `Result<(), E>` | | **Value Extraction** | Check `if (r.ok())`, then `*r` / `std::move(*r)` | Check `if (r.has_value())`, then `*r` / `std::move(*r)` | Check `if err == nil`, then read `v` | `match`, `if let`, or postfix `?` operator | | **Error Propagation** | `RETURN_IF_ERROR(expr)` / `ASSIGN_OR_RETURN(v, expr)` (macros) | Manual `if (!r) return std::unexpected(r.error());` | Explicit `if err != nil { return zero, err }` | **`expr?`** (built-in postfix language operator) | | **Preventing Ignored Errors** | `[[nodiscard]]` compiler warning/error | `[[nodiscard]]` support | Unused variable compiler error unless explicitly discarded with `_` | `#[must_use]` warning + impossible to read `T` without unwrapping the `enum` | ### 2. Key Architectural Differences 1. **Go `(T, error)` vs. `absl::StatusOr` / Rust `Result` (Product Type vs. Sum Type):** - **Go** returns a tuple `(T, error)`. Even when an error occurs, the first element (`T`) must still be constructed as its zero value (`0`, `""`, `nil`). Moreover, if a programmer forgets `if err != nil`, nothing in the type system prevents reading the invalid zero value `v`. - **`absl::StatusOr`** and **Rust `Result`** are **disjoint sum types**. When an error is returned, `T` is never constructed at all (requiring no default constructor), and the value is encapsulated inside the wrapper until `.ok()` or pattern matching is performed. 2. **Rust's `?` Operator vs. C++'s `ASSIGN_OR_RETURN`:** - **Rust** provides first-class language syntax (`?`): `let user = fetch_user(id)?;` unwraps `Ok(T)` into `user` or immediately returns `Err(e)` from the enclosing function. - Because C++ lacks a built-in postfix propagation operator, **`ASSIGN_OR_RETURN(UserProfile user, FetchUserProfile(id));` serves as the direct C++ equivalent of Rust's `let user = fetch_user(id)?;`**. 3. **`absl::StatusOr` vs. C++23 `std::expected`:** - The design of `absl::StatusOr` heavily inspired C++23's `` (`std::expected`). - While `std::expected` parameterizes the error type `E`, `absl::StatusOr` intentionally standardizes the error type on `absl::Status`. This allows errors to propagate across module and library boundaries seamlessly without requiring manual error-type conversion glue at every layer. ### 3. The Exact Same Function in All Four Models ```cpp // [1] C++ (Open-Source Abseil: absl::StatusOr) absl::StatusOr ReadUserAge(int id) { ASSIGN_OR_RETURN(std::string raw_json, FetchUserJson(id)); ASSIGN_OR_RETURN(int age, ParseAgeField(raw_json)); RETURN_IF_ERROR(ValidateAgeRange(age)); return age; } ``` ```cpp // [2] C++23 Standard (: std::expected) #include #include std::expected ReadUserAge(int id) { auto raw_json = FetchUserJson(id); if (!raw_json) return std::unexpected(raw_json.error()); auto age = ParseAgeField(*raw_json); if (!age) return std::unexpected(age.error()); if (auto valid = ValidateAgeRange(*age); !valid) { return std::unexpected(valid.error()); } return *age; } ``` ```go // [3] Go: (T, error) multi-return + if err != nil func ReadUserAge(id int) (int, error) { rawJSON, err := FetchUserJSON(id) if err != nil { return 0, err } age, err := ParseAgeField(rawJSON) if err != nil { return 0, err } if err := ValidateAgeRange(age); err != nil { return 0, err } return age, nil } ``` ```rust // [4] Rust: Result + ? operator fn read_user_age(id: i32) -> Result { let raw_json = fetch_user_json(id)?; let age = parse_age_field(&raw_json)?; validate_age_range(age)?; Ok(age) } ```