Programming Search⌘K

Conceptcore

Error propagation

Also called propagating errors, passing errors up the call stack, error bubbling, rethrowing, wrapping errors.

Error propagation passes an error from the function that finds it up the call stack to a function that can handle it, often with more context added on the way.

Applies to
core-languages

Idea

The function that finds an error is often not the right place to handle it. A function that parses a number does not know if the number came from a file, a form or a network message, so it cannot choose what to tell the user. Error propagation passes the error up the call stack to a caller that knows enough to handle it.

The Rust book describes it so: "When a function’s implementation calls something that might fail, instead of handling the error within the function itself, you can return the error to the calling code so that it can decide what to do. This is known as propagating the error"1.

def parse_port(text):
    if not text.isdigit():
        raise ValueError(f"not a number: {text!r}")
    return int(text)


def load_config(lines):
    return {key: parse_port(value) for key, value in (line.split("=") for line in lines)}


def main():
    try:
        print(load_config(["port=8080"]))
        print(load_config(["port=x"]))
    except ValueError as e:
        print(f"bad config: {e}")


main()
Output
{'port': 8080}
bad config: not a number: 'x'

parse_port finds the error, and load_config has no code for it. The exception goes up through load_config to main, which handles it.

How it works

Each error model moves the error up the stack in its own way.

  • Exceptions. The run-time system moves the error. In Java, "control is transferred from the code that caused the exception to the nearest dynamically enclosing catch clause"2. In C#, "the CLR will unwind the stack, looking for a method with a catch block for the specific exception type"3. The functions in between need no code: the Java tutorial says that a method can "duck any exceptions thrown within it, thereby allowing a method farther up the call stack to catch it"4.
  • Error values. Each function returns the error, and each caller tests it and returns it again. Rust shortens this with the operator ?: "If the value is an Err, the Err will be returned from the whole function as if we had used the return keyword so that the error value gets propagated to the calling code"1. Go writes the test out, as if err != nil followed by a return5.
  • Error codes. Each function returns a code, and each caller must test it and return it. The Java tutorial shows this with error codes: each method in the chain must "propagate the error codes returned by readFile up the call stack until the error codes finally reach method1—the only method that is interested in them"4.

Adding context

A low-level error message is often not enough. The Go blog says that "It is the error implementation’s responsibility to summarize the context"6: the error from os.Open "formats as “open /etc/passwd: permission denied,” not just “permission denied.”"6. Each layer that passes the error up can add what it knows: the file, the line, the request.

To add context and keep the original error, a function wraps it. The new error holds a message and a reference to the cause.

  • Python: raise NewError(...) from e. The tutorial says that this "can be useful when you are transforming exceptions"7.
  • JavaScript: new Error(message, { cause: e }). The property cause gives the "reason why the current error is thrown — usually another caught error"8.
  • Java and C#: a constructor argument for the cause, which C# calls the inner exception9.
  • Go: fmt.Errorf with the verb %w. With this verb, "the error returned by fmt.Errorf will have an Unwrap method returning the argument of %w"5.
  • Rust: ? passes the error through the from function, so "the error type received is converted into the error type defined in the return type of the current function"1. map_err can add a message first.

In languages

LanguageVerdictNote
PythonNative
C++Native
JavaNative
CAbsent
C#Native
JavaScriptNative
TypeScriptNative
GoNative
RustNative
KotlinNativeAn exception goes up the call stack to the nearest matching catch. Kotlin has no checked exceptions, so a function type does not list the exceptions that pass through it. No example file exists because kotlinc is not installed.
SQLIdiomAn error in a statement goes back to the client or to the calling procedure. In procedural dialects, a handler such as a DECLARE ... HANDLER block or an EXCEPTION section can catch it. No example file exists.
BashIdiom
PowerShellNativeA terminating error goes up to the nearest try/catch or trap. A non-terminating error does not stop the script unless -ErrorAction Stop makes it terminating. No example file exists because pwsh is not installed.
HTMLDoes not applyHTML has no functions or call stack.
CSSDoes not applyCSS has no functions or call stack.
Regular expressionsDoes not applyA regular expression has no functions or call stack, so there is nothing to propagate.
  • Python, JavaScript, TypeScript, Java, C#, C++ propagate exceptions without code in the functions in between. Java also checks at compile time that each checked exception is caught or declared, so each method that lets one pass shows it in its throws clause2.
  • Go returns errors as values, and each caller passes an error up with return. %w wraps an error with context5.
  • Rust returns errors in Result, and the operator ? propagates them1.
  • C passes error codes by hand, with a test after each call4.
  • Bash passes exit statuses by hand. The option -e makes the shell exit at once when a pipeline returns a status that is not zero10. This stops the whole script on the first failure, but it adds no context.

Node.js lists several mechanisms side by side, because "How these errors are reported and handled depends entirely on the type of Error and the style of the API that is called"11.

PythonGitHub
class ConfigError(Exception):
    pass


def parse_port(text):
    if not (text.isascii() and text.isdigit()):
        raise ValueError(f"not a number: {text}")
    return int(text)


def load_config(line):
    value = line.partition("=")[2]
    try:
        return parse_port(value)
    except ValueError as e:
        # Add context, and keep the original error as the cause.
        raise ConfigError(f"config line '{line}'") from e


for line in ["port=8080", "port=x"]:
    try:
        print(f"port {load_config(line)}")
    except ConfigError as e:
        print(f"error: {e}: {e.__cause__}")
Output
port 8080
error: config line 'port=x': not a number: x
  • Verdict: native. An exception goes up the call stack until a matching except clause catches it. raise ... from e adds context and keeps the first exception as __cause__, and the traceback shows both.
#include <iostream>
#include <stdexcept>
#include <string>

int parse_port(const std::string& text) {
    if (text.empty() || text.find_first_not_of("0123456789") != std::string::npos) {
        throw std::invalid_argument("not a number: " + text);
    }
    return std::stoi(text);
}

int load_config(const std::string& line) {
    std::string value = line.substr(line.find('=') + 1);
    try {
        return parse_port(value);
    } catch (const std::invalid_argument& e) {
        // Add context to the message.
        throw std::runtime_error("config line '" + line + "': " + e.what());
    }
}

int main() {
    for (std::string line : {"port=8080", "port=x"}) {
        try {
            int port = load_config(line);
            std::cout << "port " << port << "\n";
        } catch (const std::runtime_error& e) {
            std::cout << "error: " << e.what() << "\n";
        }
    }
}
Output
port 8080
error: config line 'port=x': not a number: x
  • Verdict: native. An exception goes up the stack to the nearest matching handler, and functions in between need no code for it. Here the new exception copies the old message into its own; it does not keep the original object.
JavaGitHub
public class Main {
    static class ConfigException extends Exception {
        ConfigException(String message, Throwable cause) {
            super(message, cause);
        }
    }

    static int parsePort(String text) {
        if (!text.matches("[0-9]+")) {
            throw new IllegalArgumentException("not a number: " + text);
        }
        return Integer.parseInt(text);
    }

    // The checked exception must be declared, so each caller sees it.
    static int loadConfig(String line) throws ConfigException {
        String value = line.substring(line.indexOf('=') + 1);
        try {
            return parsePort(value);
        } catch (IllegalArgumentException e) {
            throw new ConfigException("config line '" + line + "'", e);
        }
    }

    public static void main(String[] args) {
        for (String line : new String[] {"port=8080", "port=x"}) {
            try {
                System.out.println("port " + loadConfig(line));
            } catch (ConfigException e) {
                System.out.println("error: " + e.getMessage() + ": " + e.getCause().getMessage());
            }
        }
    }
}
Output
port 8080
error: config line 'port=x': not a number: x
  • Verdict: native. An exception goes up the stack to the nearest matching catch. A checked exception such as ConfigException must appear in the throws clause of each method that lets it pass. The constructor argument cause keeps the original exception.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

/* Each function returns 0 for success and -1 for an error, with a message in msg. */
static int parse_port(const char *text, int *port, char *msg, size_t n) {
    if (*text == '\0' || strspn(text, "0123456789") != strlen(text)) {
        snprintf(msg, n, "not a number: %s", text);
        return -1;
    }
    *port = atoi(text);
    return 0;
}

static int load_config(const char *line, int *port, char *msg, size_t n) {
    const char *eq = strchr(line, '=');
    char inner[100];
    if (parse_port(eq ? eq + 1 : "", port, inner, sizeof inner) != 0) {
        snprintf(msg, n, "config line '%s': %s", line, inner);
        return -1;
    }
    return 0;
}

int main(void) {
    const char *lines[] = {"port=8080", "port=x"};
    for (int i = 0; i < 2; i++) {
        int port = 0;
        char msg[200];
        if (load_config(lines[i], &port, msg, sizeof msg) != 0) {
            printf("error: %s\n", msg);
            continue;
        }
        printf("port %d\n", port);
    }
    return 0;
}
Output
port 8080
error: config line 'port=x': not a number: x
  • Verdict: absent. C has no mechanism that carries an error up the stack. Each function tests the result of each call and returns its own code, and the message is passed in a buffer.
using System;

foreach (string line in new[] { "port=8080", "port=x" })
{
    try
    {
        Console.WriteLine($"port {LoadConfig(line)}");
    }
    catch (ConfigException e)
    {
        Console.WriteLine($"error: {e.Message}: {e.InnerException!.Message}");
    }
}

static int ParsePort(string text)
{
    if (text.Length == 0) throw new FormatException("not a number: ");
    foreach (char c in text)
    {
        if (c < '0' || c > '9') throw new FormatException($"not a number: {text}");
    }
    return int.Parse(text);
}

static int LoadConfig(string line)
{
    string value = line.Substring(line.IndexOf('=') + 1);
    try
    {
        return ParsePort(value);
    }
    catch (FormatException e)
    {
        // Add context, and keep the original exception as the inner exception.
        throw new ConfigException($"config line '{line}'", e);
    }
}

class ConfigException : Exception
{
    public ConfigException(string message, Exception inner) : base(message, inner) { }
}
Output
port 8080
error: config line 'port=x': not a number: x
  • Verdict: native. The runtime unwinds the stack until it finds a matching catch block. A new exception keeps the original one in InnerException. To pass the same exception on, a catch block uses throw;, which keeps the stack trace.
JavaScriptGitHub
function parsePort(text) {
  if (!/^[0-9]+$/.test(text)) throw new Error(`not a number: ${text}`);
  return Number(text);
}

function loadConfig(line) {
  const value = line.slice(line.indexOf("=") + 1);
  try {
    return parsePort(value);
  } catch (e) {
    // Add context, and keep the original error as the cause.
    throw new Error(`config line '${line}'`, { cause: e });
  }
}

for (const line of ["port=8080", "port=x"]) {
  try {
    console.log(`port ${loadConfig(line)}`);
  } catch (e) {
    console.log(`error: ${e.message}: ${e.cause.message}`);
  }
}
Output
port 8080
error: config line 'port=x': not a number: x
  • Verdict: native. A thrown error goes up the call stack to the nearest catch. The option cause of the Error constructor keeps the original error, so that its stack trace stays available to a higher handler.
TypeScriptGitHub
function parsePort(text: string): number {
  if (!/^[0-9]+$/.test(text)) throw new Error(`not a number: ${text}`);
  return Number(text);
}

function loadConfig(line: string): number {
  const value = line.slice(line.indexOf("=") + 1);
  try {
    return parsePort(value);
  } catch (e) {
    // Add context, and keep the original error as the cause.
    throw new Error(`config line '${line}'`, { cause: e });
  }
}

for (const line of ["port=8080", "port=x"]) {
  try {
    console.log(`port ${loadConfig(line)}`);
  } catch (e) {
    const err = e as Error;
    const cause = err.cause as Error;
    console.log(`error: ${err.message}: ${cause.message}`);
  }
}
Output
port 8080
error: config line 'port=x': not a number: x
  • Verdict: native. As in JavaScript, an error goes up the stack to the nearest catch. The caught value has the type unknown, so the code gives it a type before it reads message and cause. A function type does not show which errors the function can throw.
package main

import (
	"fmt"
	"strconv"
	"strings"
)

func parsePort(text string) (int, error) {
	n, err := strconv.Atoi(text)
	if err != nil || n < 0 {
		return 0, fmt.Errorf("not a number: %s", text)
	}
	return n, nil
}

func loadConfig(line string) (int, error) {
	_, value, _ := strings.Cut(line, "=")
	port, err := parsePort(value)
	if err != nil {
		// Add context, and wrap the original error with %w.
		return 0, fmt.Errorf("config line '%s': %w", line, err)
	}
	return port, nil
}

func main() {
	for _, line := range []string{"port=8080", "port=x"} {
		port, err := loadConfig(line)
		if err != nil {
			fmt.Println("error:", err)
			continue
		}
		fmt.Println("port", port)
	}
}
Output
port 8080
error: config line 'port=x': not a number: x
  • Verdict: native. Each function returns its error, and each caller tests it and returns it up with return. The verb %w in fmt.Errorf wraps the error, so errors.Is and errors.As can still find the original in the chain.
RustGitHub
fn parse_port(text: &str) -> Result<u16, String> {
    text.parse::<u16>().map_err(|_| format!("not a number: {text}"))
}

fn load_config(line: &str) -> Result<u16, String> {
    let value = line.split_once('=').map_or("", |(_, v)| v);
    // map_err adds context, and ? returns the error to the caller.
    let port = parse_port(value).map_err(|e| format!("config line '{line}': {e}"))?;
    Ok(port)
}

fn main() {
    for line in ["port=8080", "port=x"] {
        match load_config(line) {
            Ok(port) => println!("port {port}"),
            Err(e) => println!("error: {e}"),
        }
    }
}
Output
port 8080
error: config line 'port=x': not a number: x
  • Verdict: native. The operator ? returns the error early from the function, so the caller gets it. The type Result shows in each signature that the function can fail.
BashGitHub
parse_port() {
  case $1 in
    '' | *[!0-9]*)
      echo "not a number: $1"
      return 1
      ;;
  esac
  echo "$1"
}

load_config() {
  local line=$1 out
  if ! out=$(parse_port "${line#*=}"); then
    echo "config line '$line': $out"
    return 1
  fi
  echo "$out"
}

for line in "port=8080" "port=x"; do
  if out=$(load_config "$line"); then
    echo "port $out"
  else
    echo "error: $out"
  fi
done
Output
port 8080
error: config line 'port=x': not a number: x
  • Verdict: idiom. A function returns a status, and each caller tests it with if or || and returns a status of its own. set -e makes the shell exit when a command fails, but it does not add context.
  • Where to handle. The C++ Core Guidelines say: "Let an exception propagate until it reaches a function that can handle it"12. A function that cannot do anything useful with an error passes it on.
  • Whether to wrap. Wrapping exposes the original error to callers. The Go blog advises: "Wrap an error to expose it to callers. Do not wrap an error when doing so would expose implementation details."5
  • Rethrowing. A handler can catch an error, do some cleanup, and throw it again. In C#, a handler should "use the throw statement without specifying the exception" to keep the stack trace; with throw e, "the stack trace is restarted at the current method"9.

Pitfalls

Swallowing an error

A function that catches an error and returns a default stops the propagation. The caller gets a value that looks correct.

This code runs but gives a wrong answer on purpose.

def parse_port(text):
    try:
        return int(text)
    except ValueError:
        return 0


port = parse_port("x")
print(f"listening on port {port}")
Output
listening on port 0

The program goes on with port 0, and no one sees the bad input. If a function cannot handle an error, it should let it propagate.

Losing the cause when adding context

In Go, %v copies only the text of the error. The Go blog says that "Creating a new error with fmt.Errorf discards everything from the original error except the text"5.

This code runs but gives a wrong answer on purpose.

package main

import (
	"errors"
	"fmt"
	"io/fs"
	"os"
)

func readConfig(path string) error {
	_, err := os.ReadFile(path)
	if err != nil {
		return fmt.Errorf("read config: %v", err)
	}
	return nil
}

func main() {
	err := readConfig("/no/such/config")
	fmt.Println("not found:", errors.Is(err, fs.ErrNotExist))
}
Output
not found: false

The file does not exist, but the caller cannot see it, because %v made a new error with only the text. With %w, errors.Is finds the original error in the chain and the program prints true5.

Catching too early

A try block around each call makes the code long, and the handler often has nothing useful to do. The Core Guidelines say: "Catching an exception in a function that cannot take a meaningful recovery action leads to complexity and waste."12

Cost

With exceptions, the functions in between have no code for the error, so only the methods that care about errors have to detect them4. With error values and codes, each call that can fail needs a test, and the Java tutorial notes that with codes even methods that are not interested in the error must test and return it4.

History

On 17 October 2019, Damien Neil and Jonathan Amsterdam described the error wrapping of Go 1.13 on the Go blog. They wrote that "Go 1.13 introduces new features to the errors and fmt standard library packages to simplify working with errors that contain other errors"5, including the verb %w and the functions errors.Is and errors.As.

References

  1. Recoverable Errors with Result, The Rust Programming Language, Propagating Errors; A Shortcut for Propagating Errors
  2. Chapter 11. Exceptions, The Java Language Specification, Java SE 25 Edition, 11.3 Run-Time Handling of an Exception
  3. Exceptions and Exception Handling, C# documentation, Exceptions overview
  4. Advantages of Exceptions, The Java Tutorials, Advantage 2
  5. Working with Errors in Go 1.13, The Go Blog, Wrapping errors with %w; Whether to Wrap
  6. Error handling and Go, The Go Blog, The error type
  7. Errors and Exceptions, The Python Tutorial, 8.5 Exception Chaining
  8. Error, MDN Web Docs, Instance properties (cause); Wrapping errors
  9. Best practices for exceptions, .NET documentation, Capture and rethrow exceptions properly; Wrap exceptions
  10. Bash Reference Manual, 4.3.1 The Set Builtin (-e)
  11. Errors, Node.js documentation, Error propagation and interception
  12. C++ Core Guidelines, E.17

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.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/ME8J17/text.yaml