Error Handling in C++: Abseil Status, StatusOr<T> & 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<T>, and how this design maps directly to Go’s (T, error), Rust’s Result<T, E>, and C++23’s std::expected<T, E>.
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) disable exceptions via -fno-exceptions and rely on explicit error return values.
Three Practical Limitations of C++ Exceptions#
- 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.
- Looking at
- Fragile Exception Safety Across Large Codebases:
- Unless every intermediate frame strictly adheres to RAII 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.
- 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.
- While “zero-cost exceptions” optimize the non-throwing happy path, actually throwing an exception incurs thousands of CPU cycles traversing unwind tables (
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 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.
- On success (
[[nodiscard]]Enforcement:absl::Statusis annotated with[[nodiscard]], so ignoring a returnedStatustriggers 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#
#include <iostream>
#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<T>: 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<T>.
- Header:
#include "absl/status/statusor.h" - Core Concept (Tagged Union / Sum Type):
- Holds either a valid value of type
Tor a non-OKabsl::Statusexplaining why the value is absent (conceptually similar tostd::variant<T, absl::Status>). - If
ok()istrue, a validTis guaranteed to exist; ifok()isfalse, a non-OKabsl::Statusis guaranteed to exist. Ambiguous states (both present or both empty) are unrepresentable.
- Holds either a valid value of type
Why Prefer absl::StatusOr<T> 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<T> eliminates the drawbacks of output parameters:
| Aspect | Legacy Output Parameter (Status Func(T* out)) | Modern Value Return (absl::StatusOr<T> 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<T> | Cleanly returns ownership via absl::StatusOr<std::unique_ptr<Foo>> |
| Factory Functions | Constructors cannot return errors, forcing two-phase Init() | Enables static absl::StatusOr<Foo> Create(...) so partially initialized objects never exist |
| Copy/Move Optimization | Separates declaration from population | Integrates naturally with Copy Elision & Move Semantics |
Using absl::StatusOr<T> Safely#
#include <memory>
#include <string>
#include <utility>
#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<UserProfile> FetchUserProfile(int user_id) {
if (user_id <= 0) {
// Returning an absl::Status implicitly converts it into a non-OK StatusOr<UserProfile>
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<UserProfile>
return UserProfile{.id = user_id, .name = "Alice"};
}
void ProcessUser(int user_id) {
absl::StatusOr<UserProfile> 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->, orresult.value()whenresult.ok()isfalseterminates the process immediately (crash/abort). Always verifyif (!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#
// ❌ Verbose manual error propagation
absl::StatusOr<OrderReceipt> PlaceOrderVerbose(int user_id, int item_id) {
absl::Status auth_status = VerifyAuthToken(user_id);
if (!auth_status.ok()) {
return auth_status;
}
absl::StatusOr<UserProfile> user_or = FetchUserProfile(user_id);
if (!user_or.ok()) {
return user_or.status();
}
UserProfile user = std::move(*user_or);
absl::StatusOr<InventoryItem> 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<OrderReceipt> 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:
// 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<T>); 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_RETURNbe a macro rather than a regular C++ function? It must perform two actions in the caller’s frame: (1) execute an earlyreturnfrom 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 areturnstatement 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<T> shares the exact same conceptual foundation as Go, Rust, and C++23’s std::expected<T, E>.
1. Side-by-Side Comparison Matrix#
| Dimension | C++ Abseil (absl::StatusOr<T>) | C++23 Standard (std::expected<T, E>) | Go ((T, error)) | Rust (Result<T, E>) |
|---|---|---|---|---|
| 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<void, E> | 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#
- Go
(T, error)vs.absl::StatusOr<T>/ RustResult<T, E>(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 forgetsif err != nil, nothing in the type system prevents reading the invalid zero valuev. absl::StatusOr<T>and RustResult<T, E>are disjoint sum types. When an error is returned,Tis never constructed at all (requiring no default constructor), and the value is encapsulated inside the wrapper until.ok()or pattern matching is performed.
- Go returns a tuple
- Rust’s
?Operator vs. C++’sASSIGN_OR_RETURN:- Rust provides first-class language syntax (
?):let user = fetch_user(id)?;unwrapsOk(T)intouseror immediately returnsErr(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’slet user = fetch_user(id)?;.
- Rust provides first-class language syntax (
absl::StatusOr<T>vs. C++23std::expected<T, E>:- The design of
absl::StatusOr<T>heavily inspired C++23’s<expected>(std::expected<T, E>). - While
std::expected<T, E>parameterizes the error typeE,absl::StatusOr<T>intentionally standardizes the error type onabsl::Status. This allows errors to propagate across module and library boundaries seamlessly without requiring manual error-type conversion glue at every layer.
- The design of
3. The Exact Same Function in All Four Models#
// [1] C++ (Open-Source Abseil: absl::StatusOr<T>)
absl::StatusOr<int> 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;
}// [2] C++23 Standard (<expected>: std::expected<T, E>)
#include <expected>
#include <string>
std::expected<int, std::string> 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;
}// [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
}// [4] Rust: Result<T, E> + ? operator
fn read_user_age(id: i32) -> Result<i32, AppError> {
let raw_json = fetch_user_json(id)?;
let age = parse_age_field(&raw_json)?;
validate_age_range(age)?;
Ok(age)
}