Conceptcore
Error value
Also called errors as values, error code, return code, result type.
An error value is an ordinary value that a function returns to say that it failed. The caller tests the value and decides what to do next, so the path of each failure is visible in the code.
- Applies to
- core-languages
Idea
A function can fail. A file is missing, a text is not a number, a server does not answer. The function must tell its caller. One way is to return the failure as a value, next to the result or in place of it. The caller receives the value, tests it, and decides what to do: try something else, add context and pass the error up, or report it.
This is the error value approach. It treats a failure as data, not as a jump in control. Rob Pike stated the idea for Go: "Values can be programmed, and since errors are values, errors can be programmed."1 The other approach is the exception, where the failing function throws and control jumps to a handler further up the call stack (Exception).
In Go, strconv.Atoi returns two results: the number and an error. The caller tests the error before it uses the number.
package main
import (
"fmt"
"strconv"
)
func main() {
for _, text := range []string{"8080", "x"} {
n, err := strconv.Atoi(text)
if err != nil {
fmt.Println("error:", err)
continue
}
fmt.Println("port", n)
}
}
port 8080
error: strconv.Atoi: parsing "x": invalid syntax
The if err != nil test is part of the normal code. A reader sees each place where the function can fail and what happens there.
How it works
At the level of the machine, an error value is a return value like any other. The function puts it in a register or in memory, and the caller compares it and branches. No hidden mechanism moves control. To pass an error up, each function on the path returns it to its own caller. This is the main difference from an exception, where the runtime unwinds many frames in one step.
Languages represent the error in four main ways.
| Form | How the failure is reported | Examples |
|---|---|---|
| a special value of the result | a value that cannot be a valid result, such as -1 or NULL; the reason is often in a separate variable |
C fopen and errno, Python str.find |
| a status code and an out parameter | the return value says success or failure; the result goes through a pointer or out parameter |
C status codes, C# int.TryParse16 |
| a second result | the function returns the result and an error together | Go (T, error)2 |
| a sum type | one value that is either a success with a result or a failure with an error | Rust Result<T, E>, C++ std::expected<T, E>,11 Haskell Either10 |
The special value is the oldest form, and it has two weaknesses. The caller can use the special value as if it were a result, and the reason for the failure must go elsewhere. C puts the reason in errno. A library function sets errno to a positive number when it fails, and no library function sets it to zero. So a program that wants to test errno sets it to zero before the call.9
A sum type removes both weaknesses. The value is either Ok(value) or Err(error), never both. The result is not reachable without a test of which case is present, and the compiler can check that the code handles both cases (Sum types). Haskell's Either a b follows a convention: Left holds the error and Right holds the correct value.10 C++ std::expected<T, E> holds a value of type T or an unexpected<E>.11
Passing an error up
When a function cannot handle an error, it passes the error to its caller. With error values, the code must say so at each level. Go writes an if statement that returns the error. Rust has the operator ?. On Ok(v) the expression gives v. On Err(e) the function returns at once with Err(From::from(e)).6 The call of From::from converts the error to the error type of the enclosing function, so a low-level error such as ParseIntError becomes the error type of the module.7 The operator ? also works on Option.6
use std::num::ParseIntError;
fn sum(a: &str, b: &str) -> Result<i32, ParseIntError> {
let x: i32 = a.parse()?;
let y: i32 = b.parse()?;
Ok(x + y)
}
fn main() {
println!("{:?}", sum("2", "40"));
println!("{:?}", sum("2", "forty"));
}
Ok(42)
Err(ParseIntError { kind: InvalidDigit })
Wrapping and inspection
An error that goes up through several layers needs context. "invalid syntax" says little. "load config: port setting: invalid syntax" says where it happened. Wrapping makes a new error that holds the old one. In Go, fmt.Errorf with the verb %w returns an error with an Unwrap method that gives the wrapped error.4 The errors then form a chain, or a tree when one error wraps several.3
A caller that needs to know the kind of error must look through the chain. errors.Is reports whether any error in the tree matches a target value, and errors.As finds the first error in the tree that has a given type.3 A comparison with == sees only the outer error, so it fails after wrapping (see the Go example). JavaScript has the same idea in the option cause of the Error constructor, which sets a property cause on the new error.23
Error values and exceptions
| Question | Error values | Exceptions |
|---|---|---|
| Is the failure visible in the signature? | yes, in the return type | only with checked exceptions (Java) |
| Is the failure visible at the call site? | yes: a test, or ? |
no; any call can throw |
| How does the error go up? | each level returns it | the runtime unwinds the frames |
| What happens when the caller forgets? | the error is lost, or the compiler warns | the program stops with an unhandled exception |
| What does the normal path cost? | a test and a branch after each call | nothing in a table-based implementation |
The Go designers chose error values on purpose. The FAQ says that coupling exceptions to a control structure "results in convoluted code" and that it leads programmers to label too many ordinary errors as exceptional.12 The Rust book gives a rule for the choice inside one language: return a Result when failure is expected, such as a parser that gets malformed data, and panic when the program reaches a bad state that the code should never reach.17 The second case is the subject of Panic.
In languages
| Language | Verdict | Note |
|---|---|---|
| Python | Idiom | |
| C++ | Standard library | |
| Java | Idiom | |
| C | Idiom | |
| C# | Idiom | |
| JavaScript | Idiom | |
| TypeScript | Idiom | |
| Go | Native | |
| Rust | Standard library | |
| Kotlin | Standard library | The class Result<T> holds a value or a Throwable; Kotlin reports errors with the exceptions of the JVM; no example file because kotlinc is not installed on the machine that recorded the examples. Alternative: A sealed interface with two data classes, as in the Java example. |
| SQL | Absent | A query does not return an error as a value; the engine reports a failure to the host program as a status. Alternative: The error handling of the host language, or the handlers of a procedural extension such as PL/pgSQL. |
| Bash | Idiom | Each command returns an exit status, and 0 means success; $? holds the status of the last command. Alternative: Test the status with if or ||, and set -e to stop at the first failure. |
| PowerShell | Idiom | $? holds the status of the last command and $Error holds the error records; no example file because pwsh is not installed on the machine that recorded the examples. Alternative: Try and catch for terminating errors. |
| HTML | Does not apply | Markup does not return errors. |
| CSS | Does not apply | Style rules do not return errors. |
| Regular expressions | Does not apply | A pattern does not return errors. |
The example files read a port number from a configuration in each language. The key can be missing, and the text can be invalid. The table gives the verdict for each tier 1 language.
| Language | Verdict | Form |
|---|---|---|
| Python | idiom | a union of two dataclasses tested with match; the language uses exceptions |
| JavaScript | idiom | an object with an ok field; Promise.allSettled gives outcomes as values |
| TypeScript | idiom | a discriminated union type that the checker narrows |
| Java | idiom | a sealed interface with two records; Optional for absence |
| C | idiom | a status code, a special return value and errno |
| C++ | stdlib | std::expected<T, E> and std::error_code |
| C# | idiom | the Try pattern, bool TryParse(string, out int); a record hierarchy |
| Go | native | the interface error as the last result; wrapping with %w |
| Rust | stdlib | Result<T, E> and the operator ? |
| Kotlin | stdlib | the class Result<T> |
| PowerShell | idiom | the variable $? and the error records in $Error21 |
| Bash | idiom | the exit status of each command, 0 for success, in $?20 |
| SQL | absent | the engine reports a failure to the host program as a status |
| Regex | n/a | a pattern does not return errors |
| HTML/CSS | n/a | markup and style rules do not return errors |
Kotlin has the class Result, a discriminated union of a success with a value and a failure with a Throwable.15 The failure case holds a Throwable, so Result wraps the exceptions of the JVM and does not replace them.
from dataclasses import dataclass
@dataclass(frozen=True)
class Ok[T]:
value: T
@dataclass(frozen=True)
class Err:
message: str
missing: bool = False
type Result[T] = Ok[T] | Err
def lookup(config: dict[str, str], key: str) -> Result[str]:
if key not in config:
return Err(f"missing key {key!r}", missing=True)
return Ok(config[key])
def parse_port(text: str) -> Result[int]:
if not text.isdecimal() or not 1 <= int(text) <= 65535:
return Err(f"invalid port {text!r}")
return Ok(int(text))
def port_setting(config: dict[str, str]) -> Result[int]:
match lookup(config, "port"):
case Err() as error:
return error
case Ok(text):
return parse_port(text)
for config in [{"port": "8080"}, {"port": "x"}, {}]:
match port_setting(config):
case Ok(port):
print("port", port)
case Err(missing=True):
print("use the default 80")
case Err(message):
print("error:", message)
print("find:", "port=8080".find("host"))
port 8080
error: invalid port 'x'
use the default 80
find: -1
- Verdict: idiom. Python reports errors with exceptions. A function can return a value that holds either the result or the error, and the caller tests it with
match. - The two dataclasses form a tagged union.
matchtakes the value apart with class patterns such asOk(port), because a dataclass sets__match_args__. - Nothing forces the caller to test the result. A type checker such as mypy can check the annotations, but the interpreter ignores them.
- A few built-in functions return a special value in place of an error:
str.findreturns-1, anddict.getreturnsNone.
#include <charconv>
#include <expected>
#include <map>
#include <print>
#include <string>
#include <vector>
enum class ConfigError { missing, not_a_number, out_of_range };
std::expected<std::string, ConfigError> lookup(const std::map<std::string, std::string>& config,
const std::string& key) {
auto it = config.find(key);
if (it == config.end()) {
return std::unexpected(ConfigError::missing);
}
return it->second;
}
std::expected<int, ConfigError> parse_port(const std::string& text) {
int n = 0;
auto [end, ec] = std::from_chars(text.data(), text.data() + text.size(), n);
if (ec != std::errc{} || end != text.data() + text.size()) {
return std::unexpected(ConfigError::not_a_number);
}
if (n < 1 || n > 65535) {
return std::unexpected(ConfigError::out_of_range);
}
return n;
}
int main() {
std::vector<std::map<std::string, std::string>> configs = {
{{"port", "8080"}}, {{"port", "x"}}, {{"port", "70000"}}, {}};
for (const auto& config : configs) {
auto port = lookup(config, "port").and_then(parse_port);
if (port) {
std::println("port {}", *port);
} else if (port.error() == ConfigError::missing) {
std::println("use the default 80");
} else {
std::println("error code {}", static_cast<int>(port.error()));
}
}
}
port 8080
error code 1
error code 2
use the default 80
- Verdict: stdlib.
std::expected<T, E>holds either a value of typeTor an error of typeE. It is in the standard library from C++23. and_thencalls the next function only when the previous step gave a value. Otherwise it passes the error on, as?does in Rust.std::from_charsis an older form of an error value: it returns a struct with anstd::errccode and does not throw.- Reading the value with
*portwhen it holds an error is undefined behaviour. The member functionvalue()throwsbad_expected_accessin that case.
import java.util.List;
import java.util.Map;
import java.util.Optional;
public class Main {
sealed interface Result<T> permits Ok, Err {}
record Ok<T>(T value) implements Result<T> {}
record Err<T>(String message, boolean missing) implements Result<T> {}
static Optional<String> lookup(Map<String, String> config, String key) {
return Optional.ofNullable(config.get(key));
}
static Result<Integer> portSetting(Map<String, String> config) {
Optional<String> text = lookup(config, "port");
if (text.isEmpty()) {
return new Err<>("missing key \"port\"", true);
}
try {
int n = Integer.parseInt(text.get());
if (n >= 1 && n <= 65535) {
return new Ok<>(n);
}
} catch (NumberFormatException e) {
// fall through to the error value
}
return new Err<>("invalid port \"" + text.get() + "\"", false);
}
public static void main(String[] args) {
List<Map<String, String>> configs = List.of(Map.of("port", "8080"), Map.of("port", "x"), Map.of());
for (Map<String, String> config : configs) {
String line = switch (portSetting(config)) {
case Ok<Integer>(Integer port) -> "port " + port;
case Err<Integer>(String message, boolean missing) when missing -> "use the default 80";
case Err<Integer>(String message, boolean missing) -> "error: " + message;
};
System.out.println(line);
}
}
}
port 8080
error: invalid port "x"
use the default 80
- Verdict: idiom. Java reports errors with exceptions. A sealed interface with two records gives a result type, and a
switchwith record patterns takes it apart. - The
switchhas nodefaultbranch. The compiler accepts it because the sealed interface permits onlyOkandErr, and it rejects theswitchif a permitted class is not covered. Optional<T>fromjava.utilis the standard form for a value that may be absent. It carries no reason for the absence.Integer.parseIntthrowsNumberFormatException, so the code catches the exception at the boundary and turns it into an error value.
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
enum config_error { CONFIG_OK, CONFIG_MISSING, CONFIG_NOT_A_NUMBER, CONFIG_OUT_OF_RANGE };
static const char *messages[] = {"ok", "missing key", "not a number", "out of range"};
static enum config_error parse_port(const char *text, int *port) {
if (text == NULL) {
return CONFIG_MISSING;
}
char *end;
errno = 0;
long n = strtol(text, &end, 10);
if (end == text || *end != '\0') {
return CONFIG_NOT_A_NUMBER;
}
if (errno == ERANGE || n < 1 || n > 65535) {
return CONFIG_OUT_OF_RANGE;
}
*port = (int)n;
return CONFIG_OK;
}
int main(void) {
const char *texts[] = {"8080", "x", "70000", NULL};
for (int i = 0; i < 4; i++) {
int port = 0;
enum config_error error = parse_port(texts[i], &port);
if (error == CONFIG_OK) {
printf("port %d\n", port);
} else {
printf("error %d: %s\n", error, messages[error]);
}
}
FILE *file = fopen("/no/such/dir/settings.conf", "r");
if (file == NULL) {
printf("fopen: %s\n", strerror(errno));
} else {
fclose(file);
}
}
port 8080
error 2: not a number
error 3: out of range
error 1: missing key
fopen: No such file or directory
- Verdict: idiom. C has no error type. A function returns a status code, often
0or anenumfor success, and gives the result through a pointer argument. - Many library functions return a special value, such as
NULLor-1, and store the reason inerrno.strerrorturns the number into a message. - No library function sets
errnoto zero, so the code sets it to zero beforestrtoland tests it after the call.
var configs = new[]
{
new Dictionary<string, string> { ["port"] = "8080" },
new Dictionary<string, string> { ["port"] = "x" },
new Dictionary<string, string>(),
};
foreach (var config in configs)
{
var line = PortSetting(config) switch
{
Ok(var port) => $"port {port}",
Err(_, true) => "use the default 80",
Err(var message, _) => $"error: {message}",
_ => "unknown",
};
Console.WriteLine(line);
}
static Result PortSetting(Dictionary<string, string> config)
{
if (!config.TryGetValue("port", out var text))
{
return new Err("missing key \"port\"", true);
}
if (!int.TryParse(text, out var n) || n < 1 || n > 65535)
{
return new Err($"invalid port \"{text}\"", false);
}
return new Ok(n);
}
abstract record Result;
record Ok(int Value) : Result;
record Err(string Message, bool Missing) : Result;
port 8080
error: invalid port "x"
use the default 80
- Verdict: idiom. C# reports errors with exceptions. The .NET libraries also use the Try pattern:
int.TryParseandDictionary.TryGetValuereturnbooland give the value through anoutparameter. - A record hierarchy gives a result type, and a
switchexpression with positional patterns takes it apart. - The hierarchy is not closed, so the compiler cannot prove that the
switchcovers every case. The discard arm_is needed to avoid a warning.
function lookup(config, key) {
if (!(key in config)) {
return { ok: false, error: new Error(`missing key "${key}"`), missing: true };
}
return { ok: true, value: config[key] };
}
function parsePort(text) {
const n = Number(text);
if (!Number.isInteger(n) || n < 1 || n > 65535) {
return { ok: false, error: new Error(`invalid port "${text}"`) };
}
return { ok: true, value: n };
}
function portSetting(config) {
const text = lookup(config, "port");
if (!text.ok) {
return text;
}
const port = parsePort(text.value);
if (!port.ok) {
return { ok: false, error: new Error("port setting", { cause: port.error }) };
}
return port;
}
for (const config of [{ port: "8080" }, { port: "x" }, {}]) {
const result = portSetting(config);
if (result.ok) {
console.log("port", result.value);
} else if (result.missing) {
console.log("use the default 80");
} else {
console.log(`error: ${result.error.message}: ${result.error.cause.message}`);
}
}
const settled = await Promise.allSettled([
Promise.resolve(1),
Promise.reject(new Error("timed out")),
]);
console.log(settled.map((s) => s.status).join(", "));
port 8080
error: port setting: invalid port "x"
use the default 80
fulfilled, rejected
- Verdict: idiom. JavaScript reports errors with exceptions and rejected promises. A function can return an object with an
okfield, and the caller tests the field. - The option
causeof theErrorconstructor keeps the first error inside the second one, as wrapping does in Go. Promise.allSettledturns each outcome into a value: an object withstatusset to"fulfilled"or"rejected". One failed promise does not hide the others.
type Result<T, E> = { ok: true; value: T } | { ok: false; error: E };
type ConfigError =
| { kind: "missing"; key: string }
| { kind: "invalid"; text: string };
function lookup(config: Record<string, string>, key: string): Result<string, ConfigError> {
const value = config[key];
if (value === undefined) {
return { ok: false, error: { kind: "missing", key } };
}
return { ok: true, value };
}
function portSetting(config: Record<string, string>): Result<number, ConfigError> {
const text = lookup(config, "port");
if (!text.ok) {
return text;
}
const n = Number(text.value);
if (!Number.isInteger(n) || n < 1 || n > 65535) {
return { ok: false, error: { kind: "invalid", text: text.value } };
}
return { ok: true, value: n };
}
function describe(error: ConfigError): string {
switch (error.kind) {
case "missing":
return `no ${error.key}, use the default 80`;
case "invalid":
return `invalid port "${error.text}"`;
}
}
for (const config of [{ port: "8080" }, { port: "x" }, {}]) {
const result = portSetting(config);
console.log(result.ok ? `port ${result.value}` : describe(result.error));
}
port 8080
invalid port "x"
no port, use the default 80
- Verdict: idiom. The language has no result type, but a union of object types with a literal field, a discriminated union, gives one.
- After the test
if (!text.ok), the checker narrowstextto theok: truemember, sotext.valueis allowed. Without the test,tsc --strictrejects the access tovalue. - The
switchindescribecovers everykind. When a new kind is added,tscreports that the function can end without a return value. - The types are erased at run time. The program runs as the JavaScript that remains.
package main
import (
"errors"
"fmt"
"strconv"
)
var ErrMissing = errors.New("missing key")
type PortError struct {
Text string
}
func (e *PortError) Error() string {
return fmt.Sprintf("invalid port %q", e.Text)
}
func lookup(config map[string]string, key string) (string, error) {
value, ok := config[key]
if !ok {
return "", fmt.Errorf("%w %q", ErrMissing, key)
}
return value, nil
}
func parsePort(text string) (int, error) {
n, err := strconv.Atoi(text)
if err != nil || n < 1 || n > 65535 {
return 0, &PortError{Text: text}
}
return n, nil
}
func portSetting(config map[string]string) (int, error) {
text, err := lookup(config, "port")
if err != nil {
return 0, fmt.Errorf("port setting: %w", err)
}
port, err := parsePort(text)
if err != nil {
return 0, fmt.Errorf("port setting: %w", err)
}
return port, nil
}
func main() {
configs := []map[string]string{{"port": "8080"}, {"port": "x"}, {}}
for _, config := range configs {
port, err := portSetting(config)
var portErr *PortError
switch {
case err == nil:
fmt.Println("port", port)
case errors.As(err, &portErr):
fmt.Printf("bad text %q: %v\n", portErr.Text, err)
case errors.Is(err, ErrMissing):
fmt.Println("use the default 80:", err)
}
}
}
port 8080
bad text "x": port setting: invalid port "x"
use the default 80: port setting: missing key "port"
- Verdict: native.
erroris a predeclared interface with one method,Error() string. A function returns it as its last result, andnilmeans success. fmt.Errorfwith the verb%wwraps an error: the new error adds context to the message and keeps the old error inside.errors.Isfinds a sentinel value such asErrMissinganywhere in the chain, anderrors.Asfinds an error of a given type, such as*PortError.- The compiler does not force the caller to test the error. The blank identifier
_discards it, and a call statement that ignores all the results compiles.
A wrapped error is a new value, so the operator == no longer finds the sentinel. Here the comparison is false, and the code takes the wrong branch.
This code runs but gives a wrong answer on purpose.
package main
import (
"errors"
"fmt"
)
var ErrMissing = errors.New("missing key")
func lookup(config map[string]string, key string) (string, error) {
value, ok := config[key]
if !ok {
return "", fmt.Errorf("lookup %q: %w", key, ErrMissing)
}
return value, nil
}
func main() {
_, err := lookup(map[string]string{}, "port")
fmt.Println("err == ErrMissing:", err == ErrMissing)
fmt.Println("errors.Is:", errors.Is(err, ErrMissing))
}
err == ErrMissing: false
errors.Is: true
An interface value is nil only when both its type and its value are unset. A function that returns a typed nil pointer as an error returns an interface that holds the type *PortError, so the caller sees an error.
This code runs but gives a wrong answer on purpose.
package main
import "fmt"
type PortError struct{ Text string }
func (e *PortError) Error() string { return "invalid port " + e.Text }
func check(text string) error {
var result *PortError
if text == "" {
result = &PortError{Text: text}
}
return result
}
func main() {
err := check("8080")
fmt.Println("err != nil:", err != nil)
fmt.Printf("dynamic type: %T\n", err)
}
err != nil: true
dynamic type: *main.PortError
The fix is to return the literal nil on the success path, and to give the function the result type error, not *PortError.
use std::collections::HashMap;
use std::fmt;
use std::num::ParseIntError;
#[derive(Debug)]
enum ConfigError {
Missing(String),
NotANumber(ParseIntError),
OutOfRange(u32),
}
impl fmt::Display for ConfigError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
ConfigError::Missing(key) => write!(f, "missing key {key:?}"),
ConfigError::NotANumber(e) => write!(f, "not a number: {e}"),
ConfigError::OutOfRange(n) => write!(f, "port {n} is out of range"),
}
}
}
impl From<ParseIntError> for ConfigError {
fn from(e: ParseIntError) -> Self {
ConfigError::NotANumber(e)
}
}
fn lookup<'a>(config: &HashMap<&str, &'a str>, key: &str) -> Result<&'a str, ConfigError> {
config
.get(key)
.copied()
.ok_or_else(|| ConfigError::Missing(key.to_string()))
}
fn port_setting(config: &HashMap<&str, &str>) -> Result<u16, ConfigError> {
let text = lookup(config, "port")?;
let n: u32 = text.parse()?;
if n == 0 || n > 65535 {
return Err(ConfigError::OutOfRange(n));
}
Ok(n as u16)
}
fn main() {
let configs = [
HashMap::from([("port", "8080")]),
HashMap::from([("port", "x")]),
HashMap::from([("port", "70000")]),
HashMap::new(),
];
for config in &configs {
match port_setting(config) {
Ok(port) => println!("port {port}"),
Err(ConfigError::Missing(key)) => println!("no {key}, use the default 80"),
Err(e) => println!("error: {e}"),
}
}
}
port 8080
error: not a number: invalid digit found in string
error: port 70000 is out of range
no port, use the default 80
- Verdict: stdlib.
Result<T, E>is an enum of the standard library with the variantsOk(T)andErr(E). The operator?is part of the language. ?returns early with the error. It converts the error withFrom::from, so theParseIntErrorofparsebecomes aConfigErrorthrough theFromimplementation.- The
matchinmainmust cover every variant. A new variant ofConfigErrormakes the compiler point at eachmatchthat does not handle it. Resultis marked#[must_use], so the compiler warns when a caller drops aResultwithout looking at it.
unwrap turns an error value into a panic. It is for prototypes, tests, and cases where the program knows that the value is Ok. Here the text is not a number, so the program stops with a panic.
This code panics, on purpose.
fn main() {
let port: u16 = "x".parse().unwrap();
println!("port {port}");
}
Variations and related ideas
- Absence without a reason.
Optionin Rust,Optionalin Java and a nullable type say only that a value is missing. They suit a lookup that may find nothing, not a failure with a cause (Null reference). - Sticky errors. Pike's
errWriterstores the first error and turns each later write into a no-op. The caller tests the error once at the end, in place of after each write.1 - Joined errors.
errors.Joinin Go makes one error from several and drops thenilones.3Promise.allSettledin JavaScript gives a snapshot of the state of each promise after all of them have settled.24 Both suit a batch, where one failure should not hide the others. - Chaining with functions.
and_thenon a C++std::expectedand on a RustResultcalls the next step only on success, and it passes an error on unchanged. This is error handling with Higher-order function. - The Try pattern. .NET methods such as
Int32.TryParsereturn a Boolean that says whether the conversion succeeded and give the result through anoutparameter.16 - Exceptions at the boundary. Code that uses error values often calls a library that throws. The Java and Python examples catch the exception at the boundary and turn it into a value.
Pitfalls
An ignored error
An error value is lost when the caller does not test it. In Go, the blank identifier _ discards the error, and a call statement may ignore all the results of the call.19 Here the text is not a number. strconv.Atoi returns 0 and an error, the error goes to _, and the program uses 0 as the port.
This code runs but gives a wrong answer on purpose.
package main
import (
"fmt"
"strconv"
)
func main() {
port, _ := strconv.Atoi("80a")
fmt.Println("listening on port", port)
}
listening on port 0
The fix is to test the error before the value is used. Rust marks Result with #[must_use], so the compiler warns when a caller drops a Result without a look at it.8 A Rust caller cannot reach the number without a match, ?, or a method such as unwrap that panics on an error (see the Rust example).
A stale errno
errno is not cleared by a call that succeeds. A program that tests errno without first setting it to zero can see the error of an earlier call.9 Here fopen fails and sets errno. Then strtol succeeds, but errno still holds the old value, and the program reports a failure that did not happen.
This code runs but gives a wrong answer on purpose.
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
int main(void) {
FILE *file = fopen("/no/such/dir/settings.conf", "r");
if (file != NULL) {
fclose(file);
}
long n = strtol("42", NULL, 10);
if (errno != 0) {
printf("strtol failed, errno is ENOENT: %d\n", errno == ENOENT);
} else {
printf("n = %ld\n", n);
}
}
strtol failed, errno is ENOENT: 1
The fix is errno = 0; right before the call, and a test of errno right after it, before any other library call. Test errno only when the function's return value says that it may have failed.
A typed nil is not a nil error
A Go interface value holds a type and a value. It is nil only when both are unset.13 A function that returns a nil pointer of a concrete error type, such as *PortError, through the result type error returns an interface that holds the type *PortError. The caller's test err != nil is then true. The Go example shows the program and its output. The fix is to return the literal nil on success.
Wrapping with the wrong verb
In Go, fmt.Errorf wraps only with %w. With %v it formats the old error as text, so errors.Is and errors.As cannot find it.4
This code runs but gives a wrong answer on purpose.
package main
import (
"errors"
"fmt"
"io/fs"
)
func main() {
wrapped := fmt.Errorf("load config: %w", fs.ErrNotExist)
formatted := fmt.Errorf("load config: %v", fs.ErrNotExist)
fmt.Println(errors.Is(wrapped, fs.ErrNotExist))
fmt.Println(errors.Is(formatted, fs.ErrNotExist))
}
true
false
Both errors print the same message, so the bug shows only when a caller tests the kind of the error.
A value read without a test
std::expected lets the caller read the value with * without a test. When the object holds an error, this breaks the precondition has_value(), and the behaviour is undefined. The member function value() throws bad_expected_access in that case.18 Rust's unwrap panics in the same situation. Both are a way back from an error value to a crash, so use them only where the code has already proved that the value is present.
Cost
- The normal path. Each call that can fail is followed by a test and a branch. The test runs on success too. An exception has no such test, and it is expensive only when it is thrown (Exception).
- Size. A sum type carries a tag and room for the larger of its two cases. A Go function returns its result and an interface value, which holds a type and a pointer to the value.13
- Allocation. In Go,
fmt.Errorfmakes a new error at each call, so wrapping adds one more error for each layer that adds context.4 A sentinel error in a package variable is made once. - Code size. Each level that passes an error up adds a branch and a return. The Rust operator
?hides the branch in the source, but the compiled code still has it.6
History
- 2015. Rob Pike published "Errors are values" on the Go blog. It showed that error handling in Go can be written as ordinary code over values, such as a writer that keeps the first error.1
- 2016. Rust 1.13 added the operator
?. It replaced the macrotry!, which did the same thing.14 - 2019. Go 1.13, released on 3 September 2019, added error wrapping: the verb
%woffmt.Errorf, and the functionserrors.Unwrap,errors.Isanderrors.As.522
References
- Rob Pike, Errors are values, The Go Blog, 12 January 2015, the errWriter example and the sentence "Values can be programmed, and since errors are values, errors can be programmed."
- The Go Programming Language Specification, Errors
- Go standard library, package errors, Overview (wrapping and the error tree), func Is, func As, func Join
- Go standard library, package fmt, func Errorf (the verb %w)
- Go 1.13 Release Notes, Error wrapping
- The Rust Reference, Operator expressions, The question mark operator (r-expr.try.intro, r-expr.try.restricted-types)
- The Rust Programming Language, Recoverable Errors with Result, A Shortcut for Propagating Errors, the ? operator (the call of the from function)
- Rust standard library, module std::result, Results must be used
- ISO/IEC 9899 working draft N3220 (C23), 7.5 Errors <errno.h>, paragraphs 2 and 3, footnote 237
- Haskell base library, Data.Either, data Either a b (the convention that Left holds an error and Right a correct value)
- Working Draft, Programming Languages, C++ (N4950, the C++23 draft), [expected.general], paragraph 1
- Go FAQ, Why does Go not have exceptions?
- Go FAQ, Why is my nil error value not equal to nil?
- Announcing Rust 1.13, The Rust Blog, 10 November 2016, The ? operator
- Kotlin standard library, class Result, the class description
- .NET API reference, Int32.TryParse Method, the summary of each overload
- The Rust Programming Language, To panic! or Not to panic!, Guidelines for Error Handling
- Working Draft, Programming Languages, C++ (N4950, the C++23 draft), [expected.object.obs], paragraphs 3 and 9 (the precondition of operator* and the exception of value)
- The Go Programming Language Specification, Expression statements
- bash(1), Linux manual page, EXIT STATUS; Special Parameters, ?
- PowerShell documentation, about_Automatic_Variables, $? and $Error
- Go Release History, go1.13 (released 2019-09-03)
- ECMA-262, ECMAScript 2026 Language Specification, 20.5.8.1 InstallErrorCause
- ECMA-262, ECMAScript 2026 Language Specification, 27.2.4.2 Promise.allSettled
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag X3P25M Edit this page History Report an error Markdown