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()
{'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, asif err != nilfollowed by areturn5. - 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 propertycausegives 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.Errorfwith 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 thefromfunction, so "the error type received is converted into the error type defined in the return type of the current function"1.map_errcan add a message first.
In languages
| Language | Verdict | Note |
|---|---|---|
| Python | Native | |
| C++ | Native | |
| Java | Native | |
| C | Absent | |
| C# | Native | |
| JavaScript | Native | |
| TypeScript | Native | |
| Go | Native | |
| Rust | Native | |
| Kotlin | Native | An 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. |
| SQL | Idiom | An 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. |
| Bash | Idiom | |
| PowerShell | Native | A 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. |
| HTML | Does not apply | HTML has no functions or call stack. |
| CSS | Does not apply | CSS has no functions or call stack. |
| Regular expressions | Does not apply | A 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
throwsclause2. - Go returns errors as values, and each caller passes an error up with
return.%wwraps 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
-emakes 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.
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__}")
port 8080
error: config line 'port=x': not a number: x
- Verdict: native. An exception goes up the call stack until a matching
exceptclause catches it.raise ... from eadds 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";
}
}
}
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.
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());
}
}
}
}
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 asConfigExceptionmust appear in thethrowsclause of each method that lets it pass. The constructor argumentcausekeeps 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;
}
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) { }
}
port 8080
error: config line 'port=x': not a number: x
- Verdict: native. The runtime unwinds the stack until it finds a matching
catchblock. A new exception keeps the original one inInnerException. To pass the same exception on, acatchblock usesthrow;, which keeps the stack trace.
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}`);
}
}
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 optioncauseof theErrorconstructor keeps the original error, so that its stack trace stays available to a higher handler.
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}`);
}
}
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 typeunknown, so the code gives it a type before it readsmessageandcause. 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)
}
}
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%winfmt.Errorfwraps the error, soerrors.Isanderrors.Ascan still find the original in the chain.
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}"),
}
}
}
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 typeResultshows in each signature that the function can fail.
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
port 8080
error: config line 'port=x': not a number: x
- Verdict: idiom. A function returns a status, and each caller tests it with
ifor||and returns a status of its own.set -emakes the shell exit when a command fails, but it does not add context.
Variations and related ideas
- 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}")
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))
}
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
- Recoverable Errors with Result, The Rust Programming Language, Propagating Errors; A Shortcut for Propagating Errors
- Chapter 11. Exceptions, The Java Language Specification, Java SE 25 Edition, 11.3 Run-Time Handling of an Exception
- Exceptions and Exception Handling, C# documentation, Exceptions overview
- Advantages of Exceptions, The Java Tutorials, Advantage 2
- Working with Errors in Go 1.13, The Go Blog, Wrapping errors with %w; Whether to Wrap
- Error handling and Go, The Go Blog, The error type
- Errors and Exceptions, The Python Tutorial, 8.5 Exception Chaining
- Error, MDN Web Docs, Instance properties (cause); Wrapping errors
- Best practices for exceptions, .NET documentation, Capture and rethrow exceptions properly; Wrap exceptions
- Bash Reference Manual, 4.3.1 The Set Builtin (-e)
- Errors, Node.js documentation, Error propagation and interception
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag ME8J17 Edit this page History Report an error Markdown