Errors: returned values and exceptions

Parsing a number is the smallest task that can fail, and the two languages answer it in opposite ways. C++ has exceptions that leave the signature and a caller may forget; since C++23 it also has std::expected, which puts the failure in the return type. Go has one answer: the error is the last return value, the caller checks it, and the compiler does not force the check but a reviewer does.

An exception nobody catches

std::stoi throws std::invalid_argument on text that is not a number. The first call succeeds, the second does not, and because nothing catches it the program ends in std::terminate.

#include <iostream> #include <stdexcept> #include <string> int parse(const std::string& text) { return std::stoi(text); } int main() { std::cout << parse("42") << "\n"; std::cout << parse("forty-two") << "\n"; std::cout << "not reached\n"; }

g++ -std=c++23 -O2 -Wall -Wextra throwing.cpp -o throwing
./throwing; echo "status: $?"

42
terminate called after throwing an instance of 'std::invalid_argument'
what(): stoi
status: 134

Status 134 is 128 plus the signal number of SIGABRT. Nothing after the failing call ran: no cleanup, no message written by the program, no chance to skip one bad row of a file. That is the price of an exception that reaches main, and the reason the C++ guidelines ask for a catch at the boundary of a thread or a program.

std::expected, the C++23 answer

The same function can return a value or an error, and the caller sees which in the type. There is no exception and no hidden exit path; the failure is read with if like any other value.

#include <charconv> #include <expected> #include <iostream> #include <string> #include <system_error> std::expected<int, std::string> parse(const std::string& text) { int value = 0; const char* end = text.data() + text.size(); auto [ptr, ec] = std::from_chars(text.data(), end, value); if (ec != std::errc{} || ptr != end) { return std::unexpected("parse " + text + ": not a number"); } return value; } int main() { if (auto number = parse("42")) { std::cout << *number << "\n"; } if (auto number = parse("forty-two")) { std::cout << *number << "\n"; } else { std::cout << number.error() << "\n"; } }

g++ -std=c++23 -O2 -Wall -Wextra expected.cpp -o expected
./expected; echo "status: $?"

42
parse forty-two: not a number
status: 0

std::expected is the closest thing C++ has to a Go error return, and it is three years old. Code that must build with C++17 uses a pointer, a std::optional, an error_code out-parameter or a bool return, and each project picks its own. Go made one of those choices once and put it in the language, which is a large part of why Go code from two companies looks alike.

Error values in Go

strconv.Atoi returns an error, and fmt.Errorf with %w wraps it with context while keeping the original inside. The caller reads the pair, prints both parts, and asks whether the cause is a syntax error with errors.Is.

package main import ( "errors" "fmt" "strconv" ) func parse(text string) (int, error) { n, err := strconv.Atoi(text) if err != nil { return 0, fmt.Errorf("parse %q: %w", text, err) } return n, nil } func main() { n, err := parse("42") fmt.Println(n, err) n, err = parse("forty-two") fmt.Println(n, err) fmt.Println(errors.Is(err, strconv.ErrSyntax)) }

go run ./simple

42 <nil>
0 parse "forty-two": strconv.Atoi: parsing "forty-two": invalid syntax
true

The error is a value, so it can be printed, compared, stored, sent over a channel or returned up the stack. The cost is the four lines of if err != nil that appear after almost every call, and the fact that the compiler does not stop a caller from ignoring the second value with _. A linter, not the compiler, is what enforces the check.

A typed error and errors.As

An error that carries data is a struct with an Error method and an Unwrap method, and errors.As finds it in the chain. This is how a caller reads a field of the failure without parsing a message.

package main import ( "errors" "fmt" "strconv" ) // ParseError says which text could not be parsed. type ParseError struct { Text string Err error } func (e *ParseError) Error() string { return "parse " + strconv.Quote(e.Text) + ": " + e.Err.Error() } func (e *ParseError) Unwrap() error { return e.Err } func parse(text string) (int, error) { n, err := strconv.Atoi(text) if err != nil { return 0, &ParseError{Text: text, Err: err} } return n, nil } func main() { _, err := parse("forty-two") var perr *ParseError if errors.As(err, &perr) { fmt.Println("bad text:", perr.Text) } fmt.Println(err) }

go run ./typed

bad text: forty-two
parse "forty-two": strconv.Atoi: parsing "forty-two": invalid syntax

The C++ equivalent is a catch block for a type, which is shorter at the call site and invisible in the signature. Go makes the caller write the check and gains a signature that says a call can fail. Both are reasonable; the mistake is to mix them, and a C++ codebase that returns expected in half its functions and throws in the other half is the worst of the two.

What differs and why

Question C++ exceptions C++ std::expected Go error
Is a failure visible in the signature? No Yes, in the return type Yes, as the last return value
What if the caller ignores it? The program may terminate The value is unused, the compiler may warn The value is unused, the compiler is silent
What does a non-throwing path cost? Nothing on the usual path A branch and a wider return value A branch and an interface value
Can a caller add context? Rethrow or catch and rethrow Map the error value Wrap it with %w
Where does the failure end? At a catch, or at terminate Where the caller decides Where the caller decides

Exceptions are not slow when nothing throws: a modern compiler builds tables and the normal path is untouched. They are expensive when thrown, and a hot loop that uses them for control flow is a defect. Go errors are cheap to return and cheap to check; the price is the repetition and the interface boxing. Neither language wins on speed here; they differ on who has to remember.

The Go lessons are wrapping errors with %w and errors.Is, errors.As and sentinel errors; the C++ lesson is exceptions. The next page compares generics and templates.

The C++ programs were built with g++ 15.2.0 (Alpine 15.2.0) at -O2 and the Go programs with go 1.26.10, all run on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev