Programming Search⌘K

Conceptcore

Error handling strategies

Also called error reporting strategies, error handling models, exceptions versus error codes, exceptions versus error values, error-first callbacks, EAFP, LBYL.

A program can report an error with an exception, an error value, an error code, a special value, a callback or a stop of the program. Each language prefers one strategy, and each has a cost.

Applies to
core-languages

Idea

When a function cannot do its job, it must tell its caller. There are a few ways to do it, and each language makes one of them the normal way. Python itself uses two ways for the same question. str.find returns a special value: "Return -1 if sub is not found"1. str.index raises an exception: it is "Like find(), but raise ValueError when the substring is not found"1. A third way returns the error as a value next to the result:

# 1. A special value: the result -1 means "not found".
print("abc".find("z"))

# 2. An exception: the error jumps to a handler.
try:
    "abc".index("z")
except ValueError as e:
    print(type(e).__name__)


# 3. An error value: the function returns a result and an error.
def index_of(s, sub):
    i = s.find(sub)
    if i < 0:
        return None, f"{sub!r} not found"
    return i, None


i, err = index_of("abc", "z")
print(i, err)
Output
-1
ValueError
None 'z' not found

The three ways give the same information. They differ in what the caller must write, in what happens when the caller forgets the error, and in what the type of the function says.

How it works

The main strategies are these:

  • Exceptions. The function throws an object, and the run-time system unwinds the call stack to the nearest handler for that type. The code between the throw and the handler does nothing. The C++ Core Guidelines give the rule: "Throw an exception to signal that a function can’t perform its assigned task"2.
  • Error values. The function returns the error as an ordinary value, next to the result or in place of it, and the caller tests it. Go uses a second result of type error; Rust uses a Result<T, E>. The Go FAQ explains the choice: "Go’s multi-value returns make it easy to report an error without overloading the return value"3.
  • Error codes. The function returns an integer code, and 0 means success. A shell command uses its exit status in this way.
  • Special values. The function returns a value that is not a valid result, such as -1, NULL or None. In C, the variable errno then says which error occurred; its value "is significant only when the return value of the call indicated an error"4.
  • Callbacks and promises. An asynchronous operation cannot return an error to its caller, because the caller has gone on. In Node.js, "Most asynchronous methods that accept a callback function will accept an Error object passed as the first argument to that function"5. A promise has its own state for an error: "rejected: meaning that the operation failed"6.
  • Stopping. For a bug, the program stops, or panics, and does not report the error to a caller. See Panic.

Two questions decide between them. First, is the error expected, or is it a bug? Second, does the caller usually handle it, or does it usually pass the error on?

In languages

LanguageVerdictNote
PythonNative
C++Native
JavaNative
CIdiom
C#Native
JavaScriptNative
TypeScriptNative
GoNative
RustNative
KotlinNativeKotlin uses exceptions, with no checked exceptions. The standard library has the type Result and the function runCatching for code that returns an error as a value, and functions such as toIntOrNull return null for a failure. No example file exists because kotlinc is not installed.
SQLNativeA database reports an error in a statement with an error code and a message, and the statement has no effect. Procedural extensions such as PL/pgSQL and T-SQL add exception handlers. No example file exists.
BashNative
PowerShellNativePowerShell uses two strategies. A terminating error stops the statement and goes to try and catch or a trap. A non-terminating error goes to the error stream, and the command goes on. The preference variable $ErrorActionPreference selects between them. No example file exists because pwsh is not installed.
HTMLDoes not applyHTML has no error mechanism for a program. A parser recovers from errors in markup.
CSSDoes not applyCSS has no error mechanism for a program. A parser ignores a declaration that it cannot read.
Regular expressionsDoes not applyA regular expression has no error mechanism of its own.
Language Main strategy Other strategies
Python exceptions, in the EAFP style7 special values such as -1 and None1
JavaScript, TypeScript exceptions rejected promises6; error-first callbacks in Node.js5
Java exceptions, checked and unchecked8 special values such as -1 and null
C# exceptions the Try pattern, such as int.TryParse9
C++ exceptions2 error codes
Go error values3 panics for bugs3
Rust error values of type Result10 panics for bugs10
C special values and errno4 error codes
Bash exit status11 set -e to stop on a failed command11
  • Python. Python prefers EAFP, "Easier to ask for forgiveness than permission"7. This style "assumes the existence of valid keys or attributes and catches exceptions if the assumption proves false"7, and it "contrasts with the LBYL style common to many other languages such as C"7. LBYL means "Look before you leap"7: test first, then act.
  • Java. The Java tutorial gives the rule for the two kinds of exception: "If a client can reasonably be expected to recover from an exception, make it a checked exception. If a client cannot do anything to recover from the exception, make it an unchecked exception"8.
  • C#. .NET uses exceptions, but it advises against them for common conditions: "For conditions that are likely to occur but might trigger an exception, consider handling them in a way that avoids the exception"9. "A class can provide methods or properties that enable you to avoid making a call that would trigger an exception"9.
  • Go. The Go FAQ gives the reason for error values: "coupling exceptions to a control structure, as in the try-catch-finally idiom, results in convoluted code"3, and exceptions encourage "programmers to label too many ordinary errors, such as failing to open a file, as exceptional"3. Go keeps panic and recover for "truly exceptional conditions"3.
  • Rust. The Rust Book advises: "returning Result is a good default choice when you’re defining a function that might fail"10. A panic is right when the code "could end up in a bad state"10, where "a bad state is when some assumption, guarantee, contract, or invariant has been broken"10. "However, when failure is expected, it’s more appropriate to return a Result than to make a panic! call"10.
  • Bash. With set -e, the shell exits when a pipeline "returns a non-zero status"11. But the shell does not exit for a command that is "part of the test in an if statement"11 and in some other places, so set -e is not a full strategy.
PythonGitHub
def divide(a, b):
    if b == 0:
        raise ValueError("division by zero")
    return a // b


for a, b in [(10, 2), (10, 0)]:
    try:
        print(f"{a} / {b} = {divide(a, b)}")
    except ValueError as e:
        print(f"{a} / {b}: error: {e}")
Output
10 / 2 = 5
10 / 0: error: division by zero
  • Verdict: native. Strategy: exceptions. Python raises an exception for an error, and the style called EAFP tries an operation and catches the exception. A function that returns None for a failure, such as dict.get, is the second strategy, for a case that is not an error.
#include <iostream>
#include <stdexcept>
#include <utility>

int divide(int a, int b) {
    if (b == 0) {
        throw std::domain_error("division by zero");
    }
    return a / b;
}

int main() {
    for (auto [a, b] : {std::pair{10, 2}, std::pair{10, 0}}) {
        try {
            int q = divide(a, b);
            std::cout << a << " / " << b << " = " << q << "\n";
        } catch (const std::domain_error& e) {
            std::cout << a << " / " << b << ": error: " << e.what() << "\n";
        }
    }
}
Output
10 / 2 = 5
10 / 0: error: division by zero
  • Verdict: native. Strategy: exceptions, which the C++ Core Guidelines recommend when a function cannot do its task. Code that cannot use exceptions returns an error code instead, for example a std::errc value or, since C++23, a std::expected.
JavaGitHub
public class Main {
    static int divide(int a, int b) {
        if (b == 0) {
            throw new IllegalArgumentException("division by zero");
        }
        return a / b;
    }

    public static void main(String[] args) {
        int[][] pairs = {{10, 2}, {10, 0}};
        for (int[] p : pairs) {
            try {
                System.out.println(p[0] + " / " + p[1] + " = " + divide(p[0], p[1]));
            } catch (IllegalArgumentException e) {
                System.out.println(p[0] + " / " + p[1] + ": error: " + e.getMessage());
            }
        }
    }
}
Output
10 / 2 = 5
10 / 0: error: division by zero
  • Verdict: native. Strategy: exceptions. A bad argument is a bug of the caller, so the code throws an unchecked exception. An error that the caller can be expected to recover from, such as a missing file, is a checked exception, which the method must declare with throws.
#include <stdio.h>

enum { DIV_OK = 0, DIV_BY_ZERO = 1 };

/* Returns an error code. The quotient goes through out. */
static int divide(int a, int b, int *out) {
    if (b == 0) {
        return DIV_BY_ZERO;
    }
    *out = a / b;
    return DIV_OK;
}

int main(void) {
    int pairs[2][2] = {{10, 2}, {10, 0}};
    for (int i = 0; i < 2; i++) {
        int a = pairs[i][0], b = pairs[i][1], q;
        if (divide(a, b, &q) == DIV_BY_ZERO) {
            printf("%d / %d: error: division by zero\n", a, b);
        } else {
            printf("%d / %d = %d\n", a, b, q);
        }
    }
    return 0;
}
Output
10 / 2 = 5
10 / 0: error: division by zero
  • Verdict: idiom. Strategy: error codes. The function returns a code, and the result goes through a pointer. The C library also uses a special return value, such as -1 or NULL, together with errno. Nothing makes the caller test the code.
using System;

static int Divide(int a, int b)
{
    if (b == 0)
    {
        throw new DivideByZeroException("division by zero");
    }
    return a / b;
}

foreach (var (a, b) in new[] { (10, 2), (10, 0) })
{
    try
    {
        Console.WriteLine($"{a} / {b} = {Divide(a, b)}");
    }
    catch (DivideByZeroException e)
    {
        Console.WriteLine($"{a} / {b}: error: {e.Message}");
    }
}
Output
10 / 2 = 5
10 / 0: error: division by zero
  • Verdict: native. Strategy: exceptions. For an error that occurs often, .NET also has the Try pattern: a method such as int.TryParse returns false and throws nothing, so the caller tests the result with if.
JavaScriptGitHub
function divide(a, b) {
  if (b === 0) {
    throw new RangeError("division by zero");
  }
  return Math.trunc(a / b);
}

for (const [a, b] of [[10, 2], [10, 0]]) {
  try {
    console.log(`${a} / ${b} = ${divide(a, b)}`);
  } catch (e) {
    console.log(`${a} / ${b}: error: ${e.message}`);
  }
}
Output
10 / 2 = 5
10 / 0: error: division by zero
  • Verdict: native. Strategy: exceptions for synchronous code. Asynchronous code reports an error in another way: a promise is rejected with the error, and older Node.js functions pass the error as the first argument of a callback.
TypeScriptGitHub
function divide(a: number, b: number): number {
  if (b === 0) {
    throw new RangeError("division by zero");
  }
  return Math.trunc(a / b);
}

for (const [a, b] of [[10, 2], [10, 0]]) {
  try {
    console.log(`${a} / ${b} = ${divide(a, b)}`);
  } catch (e) {
    const message = e instanceof Error ? e.message : String(e);
    console.log(`${a} / ${b}: error: ${message}`);
  }
}
Output
10 / 2 = 5
10 / 0: error: division by zero
  • Verdict: native. Strategy: exceptions, as in JavaScript. The type of divide does not show that it can throw. Some TypeScript code returns a union such as { ok: true, value: number } | { ok: false, error: string } instead, so that the type shows the error.
package main

import (
	"errors"
	"fmt"
)

func divide(a, b int) (int, error) {
	if b == 0 {
		return 0, errors.New("division by zero")
	}
	return a / b, nil
}

func main() {
	for _, p := range [][2]int{{10, 2}, {10, 0}} {
		q, err := divide(p[0], p[1])
		if err != nil {
			fmt.Printf("%d / %d: error: %v\n", p[0], p[1], err)
			continue
		}
		fmt.Printf("%d / %d = %d\n", p[0], p[1], q)
	}
}
Output
10 / 2 = 5
10 / 0: error: division by zero
  • Verdict: native. Strategy: error values. A function returns an error as its last result, and the caller tests it with if err != nil. A panic is for a bug or a state that the program cannot recover from, not for an expected error.
RustGitHub
fn divide(a: i32, b: i32) -> Result<i32, String> {
    if b == 0 {
        return Err("division by zero".to_string());
    }
    Ok(a / b)
}

fn main() {
    for (a, b) in [(10, 2), (10, 0)] {
        match divide(a, b) {
            Ok(q) => println!("{a} / {b} = {q}"),
            Err(e) => println!("{a} / {b}: error: {e}"),
        }
    }
}
Output
10 / 2 = 5
10 / 0: error: division by zero
  • Verdict: native. Strategy: error values of the type Result<T, E> for recoverable errors, and panic! for bugs. The type of the function shows that it can fail, and the caller must take the value out of the Result before it can use it.
BashGitHub
divide() {
  if (( $2 == 0 )); then
    echo "division by zero" >&2
    return 1
  fi
  echo $(( $1 / $2 ))
}

for pair in "10 2" "10 0"; do
  read -r a b <<< "$pair"
  if out=$(divide "$a" "$b" 2>&1); then
    echo "$a / $b = $out"
  else
    echo "$a / $b: error: $out"
  fi
done
Output
10 / 2 = 5
10 / 0: error: division by zero
  • Verdict: native. Strategy: exit status. A function returns a status from 0 to 255, where 0 means success, and writes its message to standard error. The caller tests the status with if. set -e makes the shell stop on a failed command, with exceptions for commands in a test.
  • Error values. Error value describes the strategy of Go and Rust in detail.
  • Exceptions. Exception describes throw, catch and unwinding.
  • Panics. Panic describe the stop of a program for a bug.
  • Assertions. Assertion find bugs, and are not a way to report expected errors.
  • Errors and bugs. Error explains the difference between an expected error and a bug, which decides the strategy.

Pitfalls

A special value that is also a valid value

A special value works only when the caller tests it. In Python, -1 is also a valid index: it names the last item. So a result of str.find that is not tested gives a wrong value and no error:

This code runs but gives a wrong answer on purpose.

s = "hello"
i = s.find("z")
print(s[i])
Output
o

Use str.index, which raises an exception, or test the result for -1.

An error-first callback that ignores the error

In Node.js, the callback receives the error as its first argument. Code that reads only the data goes on with undefined:

This code runs but gives a wrong answer on purpose.

const fs = require("node:fs");

fs.readFile("/no/such/file", (err, data) => {
  console.log(String(data));
});
Output
undefined

Test the first argument before the data: "If that first argument is not null and is an instance of Error, then an error occurred that should be handled"5.

Exceptions for ordinary results

An exception for a result that occurs often, such as a key that is not in a map, makes the normal path slow and hard to read. The Go FAQ names this risk3, and .NET advises a test or a Try method for "conditions that are likely to occur"9.

Many strategies in one program

When one library throws, a second returns codes and a third returns null, each caller must know which strategy each function uses. Choose one strategy for each layer of a program, and translate errors at the border between layers.

Cost

  • Exceptions. The normal path has no tests, and the paths that errors take are not visible at the call site. The cost of a throw depends on the implementation; Exception gives the details.
  • Error values and codes. Each call that can fail needs a test, so the code is longer. The cost at run time is a compare and a branch on each call, and the path of each error is visible.
  • Special values. They cost the least, but nothing makes the caller test them.

History

  • 2011. Andrew Gerrand's post "Error handling and Go", on 12 July 2011, described the strategy of Go: "Go code uses error values to indicate an abnormal state"12.
  • 2015. Rob Pike published "Errors are values" on the Go blog, on 12 January 201513. He wrote that the conversation about error handling in Go "often turns into a lament at the number of times the sequence"13 of tests for errors appears.

References

  1. Built-in Types, The Python Standard Library, str.find; str.index
  2. C++ Core Guidelines, E.2 Throw an exception to signal that a function can't perform its assigned task
  3. Frequently Asked Questions (FAQ), The Go Programming Language, Why does Go not have exceptions?
  4. errno(3), Linux manual page, DESCRIPTION
  5. Errors, Node.js documentation, Error propagation and interception; Error-first callbacks
  6. Promise, MDN Web Docs, Description
  7. Glossary, Python documentation, EAFP
  8. Unchecked Exceptions, The Controversy, The Java Tutorials, the last paragraph
  9. Best practices for exceptions, .NET documentation, Handle common conditions to avoid exceptions; Design classes so that exceptions can be avoided
  10. To panic! or Not to panic!, The Rust Programming Language, Guidelines for Error Handling
  11. Bash Reference Manual, 3.7.5 Exit Status; 4.3.1 The Set Builtin (-e)
  12. Andrew Gerrand, Error handling and Go, The Go Blog, 12 July 2011, Introduction
  13. Rob Pike, Errors are values, The Go Blog, 12 January 2015, the first paragraphs

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/3GV3G6/text.yaml