Programming Search⌘K

Conceptintro

Error

Also called error, errors, fault, failure, bug, error condition, expected error.

An error is a state in which a program cannot do what it was asked to do. Some errors are expected, such as bad input, and the program reports them. Others come from bugs in the code.

Applies to
core-languages

Idea

A function is called to do a job. When it cannot do the job, the program is in an error state, and some code must decide what happens next. The C++ reference names the usual cases: an error is a failure "to meet the postconditions, such as failing to produce a valid return value object"2, a failure to meet the preconditions of another function, or a failure to keep a class invariant2.

The word "error" names many things, so this page uses the terms of the IEEE vocabulary1:

  • An error is a "discrepancy between a computed, observed, or measured value or condition and the true, specified, or theoretically correct value or condition"1. A wrong value in a variable is an error.
  • A fault is a "situation that can cause errors to occur in an object"1. A fault in code is a bug: the vocabulary gives "bug" as a synonym1.
  • A failure is the "departure of system behavior from system requirements"1. "A failure can be produced when a fault is encountered"1.

Programs see two kinds of error. An expected error comes from the world outside the code: bad input, a missing file, a lost network connection. A correct program meets these errors, so it must report them and let a caller handle them. A bug comes from a fault in the code. The program cannot handle a bug in a useful way, because the code that would handle it has the same fault. This Python program shows both:

def average(xs):
    return sum(xs) / len(xs)


# An expected error: the input is empty, and Python reports it.
try:
    average([])
except ZeroDivisionError as e:
    print("reported:", type(e).__name__)


# A fault: the code divides by the wrong count, and nothing reports it.
def average_with_fault(xs):
    return sum(xs) / (len(xs) + 1)


print("expected 2.0, got", average_with_fault([1, 2, 3]))
Output
reported: ZeroDivisionError
expected 2.0, got 1.5

The first error is reported, so a caller can handle it. The fault gives a wrong value with no report, and the failure is visible only to a person who knows the correct answer.

How it works

  • Detection. Code must first find the error. A function tests its input, a library call tests the result of a system call, and the hardware or the run-time system finds some errors itself, such as a division by zero.
  • Report. The code that finds an error is often not the code that can decide what to do. So the language gives a way to send the error to a caller. The main ways are an exception, an error value, an error code, and a stop of the program. Python reports "Errors detected during execution"3 with exceptions, which "are not unconditionally fatal"3: a program can handle them.
  • Handling. A caller that receives an error can try again, use a default, report the error to a person, or pass the error on to its own caller. If no code handles an error, the program usually stops with a message.
  • When it is found. Some errors are found before the program runs. Python names "(at least) two distinguishable kinds of errors: syntax errors and exceptions"3. The parser finds a syntax error before any code runs. A type checker finds a type error before the program runs, and a test at run time finds the rest.
  • Expected errors and bugs. Some languages give the two kinds of error different mechanisms. Rust "groups errors into two major categories: recoverable and unrecoverable errors"4. "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"4.

In languages

LanguageVerdictNote
PythonNative
C++Native
JavaNative
CIdiom
C#Native
JavaScriptNative
TypeScriptNative
GoNative
RustNative
KotlinNativeKotlin reports errors with exceptions, as Java does, but it has no checked exceptions. The standard library also has the type Result for code that returns an error as a value. No example file exists because kotlinc is not installed.
SQLNativeA database reports an error in a statement with a code and a message, and the statement has no effect. The SQL standard defines SQLSTATE codes for these errors. No example file exists.
BashNative
PowerShellNativePowerShell has terminating errors, which try and catch handle, and non-terminating errors, which a command writes to the error stream and the program goes on. No example file exists because pwsh is not installed.
HTMLDoes not applyHTML has no error mechanism for a program. A parser recovers from markup errors and builds a document.
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. A pattern with bad syntax is an error of the host language, which reports it when it compiles the pattern.
Language An expected error A bug found at run time
Python an exception, such as ValueError3 an exception, such as IndexError
JavaScript, TypeScript a thrown value, usually an Error object9 an Error object, such as TypeError9
Java a checked exception, which the compiler checks8 an unchecked exception or an Error8
C# an exception10 an exception
C++ an exception or an error code2 undefined behavior, or an assertion
Go a value of type error5 a run-time panic5
Rust a Result<T, E>4 a panic4
C a special return value and errno11 undefined behavior
Bash an exit status that is not zero12 an exit status that is not zero
  • Python. An exception is an object. "Most exceptions are not handled by programs, however, and result in error messages"3, with a traceback.
  • JavaScript. "Error objects are thrown when runtime errors occur"9. A program can also throw its own Error, or a value of any other type.
  • Java. An exception is "an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions"7. The JLS divides exceptions into checked and unchecked classes, and the "compile-time checking for the presence of exception handlers is designed to reduce the number of exceptions which are not properly handled"8.
  • C#. Exceptions help "deal with any unexpected or exceptional situations that occur when a program is running"10.
  • C++. "Throwing an exception is used to signal errors from functions"2. The standard library also has functions that return an error code.
  • Go. The predeclared type error "is the conventional interface for representing an error condition, with the nil value representing no error"5. "Go code uses error values to indicate an abnormal state"6. A bug such as an index out of range causes a run-time panic: "Execution errors such as attempting to index an array out of bounds trigger a run-time panic"5.
  • Rust. "Rust doesn’t have exceptions. Instead, it has the type Result<T, E> for recoverable errors and the panic! macro that stops execution when the program encounters an unrecoverable error"4.
  • C. A function returns a special value, and the variable errno is "set by system calls and some library functions in the event of an error to indicate what went wrong"11. Its value "is significant only when the return value of the call indicated an error"11.
  • Bash. Each command has an exit status. "So while an exit status of zero indicates success, a non-zero exit status indicates failure"12.
PythonGitHub
for text in ["42", "x42"]:
    try:
        n = int(text)
    except ValueError as e:
        print(f"{text} -> error ({type(e).__name__})")
    else:
        print(f"{text} -> {n}")
Output
42 -> 42
x42 -> error (ValueError)
  • Verdict: native. Python reports an error at run time with an exception. int raises ValueError for a string that is not a number, and the except clause handles it. A syntax error is the other kind: the parser finds it before the program runs.
#include <iostream>
#include <stdexcept>
#include <string>

int main() {
    for (std::string text : {"42", "x42"}) {
        try {
            int n = std::stoi(text);
            std::cout << text << " -> " << n << "\n";
        } catch (const std::invalid_argument&) {
            std::cout << text << " -> error (std::invalid_argument)\n";
        }
    }
}
Output
42 -> 42
x42 -> error (std::invalid_argument)
  • Verdict: native. C++ has exceptions, and the standard library also uses error codes. std::stoi throws std::invalid_argument when no conversion is possible. std::from_chars reports the same error with a std::errc value and throws nothing.
JavaGitHub
public class Main {
    public static void main(String[] args) {
        for (String text : new String[] {"42", "x42"}) {
            try {
                int n = Integer.parseInt(text);
                System.out.println(text + " -> " + n);
            } catch (NumberFormatException e) {
                System.out.println(text + " -> error (" + e.getClass().getSimpleName() + ")");
            }
        }
    }
}
Output
42 -> 42
x42 -> error (NumberFormatException)
  • Verdict: native. Java reports errors with exceptions. Integer.parseInt throws NumberFormatException, an unchecked exception, so the compiler does not make the caller catch it. A checked exception, such as IOException, must be caught or declared.
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>

/* Returns 0 on success and -1 on error. The number goes through out. */
static int parse(const char *text, long *out) {
    char *end;
    errno = 0;
    long n = strtol(text, &end, 10);
    if (end == text || *end != '\0' || errno == ERANGE) {
        return -1;
    }
    *out = n;
    return 0;
}

int main(void) {
    const char *inputs[] = {"42", "x42"};
    for (int i = 0; i < 2; i++) {
        long n;
        if (parse(inputs[i], &n) == 0) {
            printf("%s -> %ld\n", inputs[i], n);
        } else {
            printf("%s -> error (return value -1)\n", inputs[i]);
        }
    }
    return 0;
}
Output
42 -> 42
x42 -> error (return value -1)
  • Verdict: idiom. C has no error mechanism in the language. A function returns a special value, such as -1 or NULL, and the library sets errno to say which error occurred. strtol gives 0 for a string with no digits, so the code tests the end pointer to find the error.
using System;

foreach (var text in new[] { "42", "x42" })
{
    try
    {
        int n = int.Parse(text);
        Console.WriteLine($"{text} -> {n}");
    }
    catch (FormatException e)
    {
        Console.WriteLine($"{text} -> error ({e.GetType().Name})");
    }
}
Output
42 -> 42
x42 -> error (FormatException)
  • Verdict: native. C# reports errors with exceptions, and has no checked exceptions. int.Parse throws FormatException for a bad string. The method int.TryParse reports the same error with a bool result instead, for code that expects bad input.
JavaScriptGitHub
function parseInteger(text) {
  const n = Number(text);
  if (!Number.isInteger(n)) {
    throw new Error(`not an integer: ${text}`);
  }
  return n;
}

for (const text of ["42", "x42"]) {
  try {
    console.log(`${text} -> ${parseInteger(text)}`);
  } catch (e) {
    console.log(`${text} -> error (${e.name})`);
  }
}
Output
42 -> 42
x42 -> error (Error)
  • Verdict: native. JavaScript reports errors with exceptions: a throw statement and try...catch. Number does not throw for a bad string; it gives NaN. So the function tests the result and throws an Error object itself.
TypeScriptGitHub
function parseInteger(text: string): number {
  const n = Number(text);
  if (!Number.isInteger(n)) {
    throw new Error(`not an integer: ${text}`);
  }
  return n;
}

for (const text of ["42", "x42"]) {
  try {
    console.log(`${text} -> ${parseInteger(text)}`);
  } catch (e) {
    const name = e instanceof Error ? e.name : "unknown";
    console.log(`${text} -> error (${name})`);
  }
}
Output
42 -> 42
x42 -> error (Error)
  • Verdict: native. TypeScript has the exceptions of JavaScript. A program can throw any value, not only an Error, so the code tests the caught value with instanceof Error before it reads name. The type of a function does not say which errors it throws.
package main

import (
	"errors"
	"fmt"
	"strconv"
)

func main() {
	for _, text := range []string{"42", "x42"} {
		n, err := strconv.Atoi(text)
		if err != nil {
			fmt.Printf("%s -> error (%v)\n", text, errors.Unwrap(err))
			continue
		}
		fmt.Printf("%s -> %d\n", text, n)
	}
}
Output
42 -> 42
x42 -> error (invalid syntax)
  • Verdict: native. Go reports an error as a value of the predeclared interface type error, returned as the last result. nil means no error. strconv.Atoi returns a *strconv.NumError that wraps strconv.ErrSyntax, and errors.Unwrap gets that cause.
RustGitHub
fn main() {
    for text in ["42", "x42"] {
        match text.parse::<i32>() {
            Ok(n) => println!("{text} -> {n}"),
            Err(e) => println!("{text} -> error ({:?})", e.kind()),
        }
    }
}
Output
42 -> 42
x42 -> error (InvalidDigit)
  • Verdict: native. Rust reports a recoverable error with the type Result<T, E>, and stops on a bug with panic!. parse returns Err with a ParseIntError, and its kind method names the cause.
BashGitHub
parse() {
  if [[ $1 =~ ^-?[0-9]+$ ]]; then
    echo "$1"
  else
    return 1
  fi
}

for text in 42 x42; do
  if n=$(parse "$text"); then
    echo "$text -> $n"
  else
    echo "$text -> error (exit status $?)"
  fi
done
Output
42 -> 42
x42 -> error (exit status 1)
  • Verdict: native. A shell command reports an error with its exit status: 0 means success, and a value from 1 to 255 means failure. if runs the else branch when the status is not 0. The shell does not stop on a failed command unless set -e is on.
  • Error values. Error value describes errors that a function returns as ordinary values, as in Go and Rust.
  • Exceptions. Exception describes errors that jump to a handler up the call stack.
  • Panics. Panic describe a stop of the program, or of one thread, for a bug.
  • Assertions. Assertion find bugs: an assertion tests a condition that must be true if the code has no fault.
  • Undefined behavior. In C and C++, some bugs have no defined result. Undefined behavior explains why such a bug can give no report at all.
  • Static checks. Static and dynamic typing explains how a type checker finds some errors before the program runs.

Pitfalls

An ignored error

An error that the program does not test gives a wrong value later, far from its cause. In Go, the blank identifier discards the error, and the value is 0:

This code runs but gives a wrong answer on purpose.

package main

import (
	"fmt"
	"strconv"
)

func main() {
	n, _ := strconv.Atoi("x42")
	fmt.Println("n =", n)
}
Output
n = 0

Test each error, or say in a comment why the program can ignore it.

A handler that hides a bug

A handler for all errors also catches errors that come from bugs. Here a misspelled name gives a NameError, and the handler turns the bug into a wrong total:

This code runs but gives a wrong answer on purpose.

def total(prices, shipping):
    try:
        return sum(prices) + shiping
    except Exception:
        return 0


print(total([10, 20], 5))
Output
0

Catch only the errors that the code expects, such as ValueError or OSError. Let a bug stop the program, or catch it in one place at the top level and report it.

A failed command that does not stop the script

A shell script goes on after a command fails. The exit status is the only report:

This code runs but gives a wrong answer on purpose.

false
echo "status $?"
echo "the script goes on"
Output
status 1
the script goes on

Test the exit status of each command that can fail, or turn on set -e, which has its own limits.

Errors for bugs and bugs for errors

A program that stops on an expected error is fragile: bad input from a user should give a message, not a crash. A program that tries to recover from a bug goes on in a state that is not correct. Use the mechanism for expected errors for the first kind, and stop on the second kind.

Cost

  • Code. Each place that can fail needs a test or a handler. In languages with error values, the tests are in the code; with exceptions, they are in fewer places, but the paths that the errors take are harder to see.
  • Run time. A test of a return value costs a compare and a branch. The cost of an exception depends on the implementation; Exception gives the details.

History

  • 1975. John B. Goodenough published a paper on exception handling in Communications of the ACM13.
  • 2011. Andrew Gerrand's post "Error handling and Go", on 12 July 2011, described the Go view: "Go code uses error values to indicate an abnormal state"6.
  • 2025. The IEEE vocabulary of software engineering separates error, fault and failure. Its definitions of error and fault come from ISO/IEC/IEEE 15026-1:2025, and one of its definitions of failure comes from IEEE 982:20241.

References

  1. SEVOCAB, Software and Systems Engineering Vocabulary, IEEE Computer Society, the entries error, fault and failure
  2. Exceptions, cppreference.com, Usage; Error handling
  3. Errors and Exceptions, The Python Tutorial, 8.1 Syntax Errors; 8.2 Exceptions
  4. Error Handling, The Rust Programming Language, the introduction of chapter 9
  5. The Go Programming Language Specification, Errors; Run-time panics
  6. Andrew Gerrand, Error handling and Go, The Go Blog, 12 July 2011, Introduction
  7. What Is an Exception?, The Java Tutorials, the whole page
  8. Chapter 11. Exceptions, The Java Language Specification, Java SE 25 Edition, 11.1.1 The Kinds of Exceptions; 11.2 Compile-Time Checking of Exceptions
  9. Error, MDN Web Docs, the first paragraph
  10. Exceptions and Exception Handling, C# fundamentals, the first paragraphs
  11. errno(3), Linux manual page, DESCRIPTION
  12. Bash Reference Manual, 3.7.5 Exit Status
  13. John B. Goodenough, Exception Handling: Issues and a Proposed Notation, Communications of the ACM 18(12), 1975, the Crossref record (author, journal, December 1975)

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