Programming Search⌘K

Conceptcore

Recoverable and unrecoverable errors

Also called recoverable error, unrecoverable error, fatal error, Result versus panic, Exception versus Error, errors versus bugs.

A recoverable error is one that a correct program expects and handles, such as a missing file. An unrecoverable error is usually a bug, and the safe action is to stop.

Applies to
core-languages

Idea

Some errors are part of the normal life of a program. A file is missing, a user types a letter where a number belongs, a server is down. A correct program meets these errors, and it can do something useful: ask again, use a default, or report the error. These errors are recoverable.

Other errors mean that the program itself is wrong. An index is past the end of an array, or a value that must never be negative is negative. The code that would handle this error was written by the same person who made the mistake, so it has no reliable way to fix it. These errors are unrecoverable, and the safe action is to stop.

The Rust Book makes this split the base of the language: "Rust groups errors into two major categories: recoverable and unrecoverable errors"1. "For a recoverable error, such as a file not found error, we most likely just want to report the problem to the user and retry the operation. Unrecoverable errors are always symptoms of bugs, such as trying to access a location beyond the end of an array, and so we want to immediately stop the program"1. This program meets a recoverable error and handles it:

use std::fs;

fn main() {
    // A recoverable error: the file may not exist.
    match fs::read_to_string("/no/such/file.txt") {
        Ok(text) => println!("read {} bytes", text.len()),
        Err(e) => println!("recovered: {:?}", e.kind()),
    }

    // A correct index. An index past the end would be a bug,
    // and Rust would stop the thread with a panic.
    let v = vec![1, 2, 3];
    let i = 2;
    println!("v[{i}] = {}", v[i]);
}
Output
recovered: NotFound
v[2] = 3

How it works

  • The test. The question is not how bad the error is, but whether a correct program can meet it. The Rust Book advises a panic when the code "could end up in a bad state"2, where "a bad state is when some assumption, guarantee, contract, or invariant has been broken"2. It adds that the bad state is "something that is unexpected, as opposed to something that will likely happen occasionally, like a user entering data in the wrong format"2.
  • The caller decides. A function often cannot know whether an error is recoverable for its caller. So the Rust Book advises: "returning Result is a good default choice when you’re defining a function that might fail"2. The caller can handle the error, or turn it into a stop: "it could decide that an Err value in this case is unrecoverable"2.
  • Stopping. A stop for a bug can unwind or abort. In Rust, a panic will by default "print a failure message, unwind, clean up the stack, and quit"3. In C, abort raises SIGABRT, which "results in the abnormal termination of the process"4 unless a handler catches it.
  • Not all bugs stop. A stop happens only where the code or the run-time system tests for the bug. In C and C++, many bugs have undefined behavior, and nothing stops the program; see Undefined behavior.

In languages

LanguageVerdictNote
PythonIdiom
C++Idiom
JavaNative
CIdiom
C#Standard library
JavaScriptAbsent
TypeScriptAbsent
GoNative
RustNative
KotlinIdiomKotlin uses exceptions for both kinds. The standard library functions require and check throw an exception for a bad argument or state, and error throws an IllegalStateException. Java Error classes such as OutOfMemoryError also reach Kotlin on the JVM. No example file exists because kotlinc is not installed.
SQLAbsentSQL has no mechanism for bugs. A statement fails with an error code, and the transaction can roll back. No example file exists.
BashIdiom
PowerShellIdiomPowerShell separates terminating errors from non-terminating errors, but both are errors to handle, not bugs. A script stops for a bug with throw or exit. No example file exists because pwsh is not installed.
HTMLDoes not applyHTML has no error mechanism for a program.
CSSDoes not applyCSS has no error mechanism for a program.
Regular expressionsDoes not applyA regular expression has no error mechanism of its own.
Language Recoverable errors Unrecoverable errors
Rust Result<T, E>5 panic!, and assert!3
Go values of type error panic, and run-time panics6
Java subclasses of Exception7 subclasses of Error78
C# exceptions Environment.FailFast9
C++ exceptions and error codes std::abort, and std::terminate10
C return values and errno abort4
Python exceptions the same exceptions, such as AssertionError11
JavaScript, TypeScript exceptions the same exceptions
Bash exit status exit
  • Rust. Rust has no exceptions; "it has the type Result<T, E> for recoverable errors and the panic! macro that stops execution when the program encounters an unrecoverable error"1. "Most errors aren’t serious enough to require the program to stop entirely"5. The method unwrap turns one into the other: "If the Result is the Err variant, unwrap will call the panic! macro for us"5.
  • Go. "Panic is a built-in function that stops the ordinary flow of control and begins panicking"12. Panics "can also be caused by runtime errors, such as out-of-bounds array accesses"12. The deferred functions run, and when the panic reaches the top of the goroutine, "the program crashes"12. A deferred call to recover can stop a panic: "Recover is a built-in function that regains control of a panicking goroutine"12.
  • Java. Java splits the classes of Throwable. "Exception is the superclass of all the exceptions from which ordinary programs may wish to recover"7. "Error is the superclass of all the exceptions from which ordinary programs are not ordinarily expected to recover"7. The API says that an Error "indicates serious problems that a reasonable application should not try to catch"8.
  • C#. Exceptions report both kinds. For a state that is too bad to go on, Environment.FailFast "Immediately terminates the process before reporting an error message"9, and the finally blocks do not run9.
  • C++. The runtime calls std::terminate "when the program cannot continue"10, for example when "An exception is thrown and not caught"10.
  • Python. Python uses exceptions for both kinds. AssertionError is "Raised when an assert statement fails"11, and a program can catch it as any other exception. Some errors that sound fatal can be handled: MemoryError is "Raised when an operation runs out of memory but the situation may still be rescued (by deleting some objects)"11.
PythonGitHub
def port_or_default(text, fallback):
    # A bad fallback is a bug in the caller: stop.
    assert 1 <= fallback <= 65535, "fallback out of range"
    # Bad text is an expected error: recover.
    try:
        return int(text), ""
    except ValueError:
        return fallback, " (not a number)"


for text in ["8080", "x"]:
    port, note = port_or_default(text, 80)
    print(f"{text} -> {port}{note}")
Output
8080 -> 8080
x -> 80 (not a number)
  • Verdict: idiom. Python uses exceptions for both kinds. The code catches ValueError, an expected error, and uses an assert for a bug. An AssertionError is also an exception, and python -O removes assert statements, so the split is a convention.
#include <charconv>
#include <cstdlib>
#include <iostream>
#include <string>

int port_or_default(const std::string& text, int fallback, std::string& note) {
    // A bad fallback is a bug in the caller: stop the program.
    if (fallback < 1 || fallback > 65535) {
        std::abort();
    }
    // Bad text is an expected error: recover.
    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()) {
        note = " (not a number)";
        return fallback;
    }
    note = "";
    return n;
}

int main() {
    for (std::string text : {"8080", "x"}) {
        std::string note;
        int port = port_or_default(text, 80, note);
        std::cout << text << " -> " << port << note << "\n";
    }
}
Output
8080 -> 8080
x -> 80 (not a number)
  • Verdict: idiom. C++ has no separate mechanism for bugs. The code reports the expected error with the std::errc value of std::from_chars, and calls std::abort for the bug. An exception that no handler catches also ends the program, through std::terminate.
JavaGitHub
public class Main {
    static int port;
    static String note;

    static void portOrDefault(String text, int fallback) {
        // A bad fallback is a bug in the caller: stop.
        if (fallback < 1 || fallback > 65535) {
            throw new AssertionError("fallback out of range");
        }
        // Bad text is an expected error: recover.
        try {
            port = Integer.parseInt(text);
            note = "";
        } catch (NumberFormatException e) {
            port = fallback;
            note = " (not a number)";
        }
    }

    public static void main(String[] args) {
        for (String text : new String[] {"8080", "x"}) {
            portOrDefault(text, 80);
            System.out.println(text + " -> " + port + note);
        }
    }
}
Output
8080 -> 8080
x -> 80 (not a number)
  • Verdict: native. Java splits Throwable into Exception, for errors that a program may recover from, and Error, for serious problems that a program should not catch. AssertionError is an Error. NumberFormatException is an Exception that the code catches.
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>

static long port_or_default(const char *text, long fallback, const char **note) {
    /* A bad fallback is a bug in the caller: stop the program. */
    if (fallback < 1 || fallback > 65535) {
        abort();
    }
    /* Bad text is an expected error: recover. */
    char *end;
    errno = 0;
    long n = strtol(text, &end, 10);
    if (end == text || *end != '\0' || errno == ERANGE) {
        *note = " (not a number)";
        return fallback;
    }
    *note = "";
    return n;
}

int main(void) {
    const char *inputs[] = {"8080", "x"};
    for (int i = 0; i < 2; i++) {
        const char *note;
        long port = port_or_default(inputs[i], 80, &note);
        printf("%s -> %ld%s\n", inputs[i], port, note);
    }
    return 0;
}
Output
8080 -> 8080
x -> 80 (not a number)
  • Verdict: idiom. C has no mechanism for either kind. A function reports an expected error with its return value, and the program calls abort for a bug, which raises SIGABRT and ends the process. assert also calls abort when its condition is false.
using System;

foreach (var text in new[] { "8080", "x" })
{
    var (port, note) = PortOrDefault(text, 80);
    Console.WriteLine($"{text} -> {port}{note}");
}

static (int, string) PortOrDefault(string text, int fallback)
{
    // A bad fallback is a bug in the caller: stop the process.
    if (fallback < 1 || fallback > 65535)
    {
        Environment.FailFast("fallback out of range");
    }
    // Bad text is an expected error: recover.
    return int.TryParse(text, out int n) ? (n, "") : (fallback, " (not a number)");
}
Output
8080 -> 8080
x -> 80 (not a number)
  • Verdict: stdlib. C# uses exceptions for most errors. For a state that the program cannot recover from, Environment.FailFast ends the process at once, and no catch or finally block runs. The expected error uses int.TryParse.
JavaScriptGitHub
function portOrDefault(text, fallback) {
  // A bad fallback is a bug in the caller: stop.
  if (!(fallback >= 1 && fallback <= 65535)) {
    throw new RangeError("fallback out of range");
  }
  // Bad text is an expected error: recover.
  const n = Number(text);
  if (!Number.isInteger(n)) {
    return [fallback, " (not a number)"];
  }
  return [n, ""];
}

for (const text of ["8080", "x"]) {
  const [port, note] = portOrDefault(text, 80);
  console.log(`${text} -> ${port}${note}`);
}
Output
8080 -> 8080
x -> 80 (not a number)
  • Verdict: absent. JavaScript has one mechanism, exceptions, for both kinds. Here the code returns the expected error as a value and throws for the bug. Nothing in the language marks a thrown Error as a bug.
TypeScriptGitHub
function portOrDefault(text: string, fallback: number): [number, string] {
  // A bad fallback is a bug in the caller: stop.
  if (!(fallback >= 1 && fallback <= 65535)) {
    throw new RangeError("fallback out of range");
  }
  // Bad text is an expected error: recover.
  const n = Number(text);
  if (!Number.isInteger(n)) {
    return [fallback, " (not a number)"];
  }
  return [n, ""];
}

for (const text of ["8080", "x"]) {
  const [port, note] = portOrDefault(text, 80);
  console.log(`${text} -> ${port}${note}`);
}
Output
8080 -> 8080
x -> 80 (not a number)
  • Verdict: absent. TypeScript has the exceptions of JavaScript and no second mechanism. The return type [number, string] shows the expected error, and the throw for the bug does not show in the type.
package main

import (
	"fmt"
	"strconv"
)

func portOrDefault(text string, fallback int) (int, string) {
	// A bad fallback is a bug in the caller: panic.
	if fallback < 1 || fallback > 65535 {
		panic("fallback out of range")
	}
	// Bad text is an expected error: recover.
	n, err := strconv.Atoi(text)
	if err != nil {
		return fallback, " (not a number)"
	}
	return n, ""
}

func main() {
	for _, text := range []string{"8080", "x"} {
		port, note := portOrDefault(text, 80)
		fmt.Printf("%s -> %d%s\n", text, port, note)
	}
}
Output
8080 -> 8080
x -> 80 (not a number)
  • Verdict: native. Go reports an expected error as an error value, and uses panic for a bug. A panic runs the deferred functions and then crashes the program, unless a deferred call to recover stops it.
RustGitHub
fn port_or_default(text: &str, fallback: u32) -> (u32, &'static str) {
    // A bad fallback is a bug in the caller: panic.
    assert!((1..=65535).contains(&fallback), "fallback out of range");
    // Bad text is an expected error: recover.
    match text.parse::<u32>() {
        Ok(n) => (n, ""),
        Err(_) => (fallback, " (not a number)"),
    }
}

fn main() {
    for text in ["8080", "x"] {
        let (port, note) = port_or_default(text, 80);
        println!("{text} -> {port}{note}");
    }
}
Output
8080 -> 8080
x -> 80 (not a number)
  • Verdict: native. Rust has a mechanism for each kind: Result<T, E> for a recoverable error, and panic! for an unrecoverable one. assert! panics when its condition is false. A panic unwinds the stack of the thread and stops it.
BashGitHub
port_or_default() {
  # A bad fallback is a bug in the caller: stop the script.
  if (( $2 < 1 || $2 > 65535 )); then
    echo "fallback out of range" >&2
    exit 70
  fi
  # Bad text is an expected error: recover.
  if [[ $1 =~ ^[0-9]+$ ]]; then
    echo "$1"
  else
    echo "$2 (not a number)"
  fi
}

for text in 8080 x; do
  echo "$text -> $(port_or_default "$text" 80)"
done
Output
8080 -> 8080
x -> 80 (not a number)
  • Verdict: idiom. The shell has only exit statuses. A function returns a status for an expected error, and exit stops the script for a bug. Inside a command substitution, as here, exit stops only the subshell, so a careful script also tests the status of the substitution.
  • Panics. Panic describes the mechanism that stops a program or a thread, and the choice between unwinding and aborting.
  • Assertions. Assertion test the conditions that only a bug can break. They are the usual way to find an unrecoverable error early.
  • Strategies. Error handling strategies compares the ways to report a recoverable error.
  • Isolation. A server can stop one request, one thread or one process for a bug, and keep the rest of the program alive. Go's recover and a top-level handler for each request work in this way.

Pitfalls

Recovering from a bug

A handler for all exceptions also catches a failed assertion. Here the bug, a call of mean with an empty list, becomes a normal result:

This code runs but gives a wrong answer on purpose.

def mean(xs):
    assert xs, "mean of an empty list"
    return sum(xs) / len(xs)


def report(xs):
    try:
        return f"mean = {mean(xs)}"
    except Exception:
        return "no data"


print(report([2, 4]))
print(report([]))
Output
mean = 3.0
no data

If an empty list is expected, test for it and return a result. If it is a bug, let the error reach the top of the program. Also, "The current code generator emits no code for an assert statement when optimization is requested at compile time"13, so python -O removes this test.

A stop for an expected error

unwrap turns a recoverable error into a panic. For input from a user, this stops the program for an error that a correct program must expect:

This code panics, on purpose.

fn main() {
    let input = "x";
    let port: u32 = input.parse().unwrap();
    println!("{port}");
}

Use match, ?, or a method such as unwrap_or for input from outside the program. Keep unwrap for values that cannot be wrong if the code is correct.

Catching Error in Java

catch (Throwable t) also catches Error, such as OutOfMemoryError and StackOverflowError. After such an error, the state of the program may be broken. Catch Exception, or a narrower class.

A recover that hides a bug

In Go, a deferred recover can turn each panic into an ordinary return. Use it at a border, such as the handler of one request, and report the panic there. Do not use it to make bugs silent.

Cost

  • Recoverable errors. Each one needs code at the call site or in a handler, and each needs a test.
  • Unrecoverable errors. A stop is cheap to write. The cost is in availability: a program that stops for each bug needs a supervisor, a restart, or isolation of the part that failed.

History

  • 2010. Andrew Gerrand's post "Defer, Panic, and Recover", on 4 August 2010, described the panic mechanism of Go and its use for a stop of the ordinary flow of control12.
  • The JLS. The Java Language Specification splits Throwable into Exception and Error: the exceptions that programs may wish to recover from, and those that they are not expected to recover from7.
  • Rust. The Rust Book makes the split between Result and panic! the first idea of its chapter on errors1.

References

  1. Error Handling, The Rust Programming Language, the introduction of chapter 9
  2. To panic! or Not to panic!, The Rust Programming Language, Guidelines for Error Handling
  3. Unrecoverable Errors with panic!, The Rust Programming Language, the first part; Unwinding the Stack or Aborting in Response to a Panic
  4. abort(3), Linux manual page, DESCRIPTION
  5. Recoverable Errors with Result, The Rust Programming Language, the first paragraph; Shortcuts for Panic on Error
  6. The Go Programming Language Specification, Run-time panics; Handling panics
  7. Chapter 11. Exceptions, The Java Language Specification, Java SE 25 Edition, 11.1.1 The Kinds of Exceptions
  8. Class Error, Java SE 25 API, the class description
  9. Environment.FailFast Method, .NET API, the summary; Examples
  10. std::terminate, cppreference.com, the reasons for a call
  11. Built-in Exceptions, The Python Standard Library, MemoryError; AssertionError
  12. Andrew Gerrand, Defer, Panic, and Recover, The Go Blog, 4 August 2010, Panic; Recover
  13. Simple statements, The Python Language Reference, 7.3 The assert statement

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