Programming Search⌘K

Conceptcore

Exception

Also called exception handling, raise and catch, throw and catch.

An exception is an object that a program raises when an operation cannot complete. Control goes up the call stack to the nearest matching handler, and the cleanup code of each frame runs on the way.

Applies to
core-languages

Idea

An operation sometimes cannot do its work. The text is not a number, the file is not there, or the connection closes. The code that finds the problem often does not know what to do about it, and the code that knows is often several calls away.1 An exception connects the two. The code that finds the problem raises (or throws) an exception, an object that describes the problem. Control leaves the operation at once and goes to the nearest handler for that kind of exception, in the same function or in one of its callers. The functions between the two end early, and they do not have to contain any code for the error.

In Python, parse_port raises ValueError for a port out of range, and int raises ValueError for text that is not a number. read_config has no handler, so the exception goes through it, and its print does not run. The handler in the loop catches both.

def parse_port(text):
    port = int(text)
    if not 1 <= port <= 65535:
        raise ValueError(f"port out of range: {port}")
    return port


def read_config(lines):
    ports = [parse_port(line) for line in lines]
    print("read", len(ports), "ports")
    return ports


for lines in (["80", "443"], ["80", "70000"], ["80", "abc"]):
    try:
        read_config(lines)
    except ValueError as e:
        print("handled:", e)
Output
read 2 ports
handled: port out of range: 70000
handled: invalid literal for int() with base 10: 'abc'

How it works

An exception mechanism has four steps.

  1. Raise. A raise or throw statement, or a failed check of the run-time system, makes an exception object and starts a search.
  2. Search. The run-time system looks for a handler that matches the exception, usually by its class. It looks first in the innermost try statement around the point of the raise, then in the try statements around that one, and then in the caller at the point of the call, up the call stack.23
  3. Unwind. The frames between the raise and the handler are removed. The cleanup code of each frame runs on the way: finally blocks, context managers and destructors.4
  4. Handle. The handler runs. Then execution continues after the try statement that contains the handler, not at the point of the raise.

This run shows the order. Each finally block runs while the exception passes through its frame, from the inside out, and then the handler runs.

def inner():
    try:
        raise KeyError("port")
    finally:
        print("finally in inner")


def middle():
    try:
        inner()
        print("not reached")
    finally:
        print("finally in middle")


try:
    middle()
except KeyError as e:
    print("handler:", repr(e))
Output
finally in inner
finally in middle
handler: KeyError('port')

When the search finds no handler, the program reports the exception and stops. C++ calls std::terminate.3 The .NET runtime ends the thread.5 Python prints a traceback and exits with a non-zero status.

Termination and resumption

In the termination model, the handler takes the place of the rest of the operation that raised. The operation cannot continue. The designers of CLU chose this model and rejected the resumption model of PL/I and Mesa, because resumption was complex and because termination was what most programs needed.6 Koenig and Stroustrup made the same choice for C++. They gave this reason: if a handler can resume, the code after if (something_wrong) throw zxc(); cannot assume that something_wrong is false.1 Python, Java, JavaScript, C# and the other languages on this page use termination.

The Common Lisp condition system separates the parts. A handler runs before the stack unwinds, in the dynamic context of the code that signalled. It can decline, and then the next handler runs.7 It can also transfer control to a restart, a named way to continue that the lower code set up.8 This gives the effect of resumption under the control of the code that signalled.

Two-phase unwinding

An implementation can search before it unwinds. The Itanium C++ ABI defines a two-phase process. In the search phase, the unwinder walks up the stack and asks the personality routine of each frame whether the frame has a handler. It does not remove any frame. If no frame has a handler, it calls terminate(). In the cleanup phase, it walks up the stack again and runs the cleanup code of each frame, up to the frame of the handler.9 A C# exception filter (catch (E e) when (condition)) also runs before the stack unwinds, so a filter that returns false leaves the stack and its trace as they were.5

Checked exceptions

In Java, the compiler checks the exceptions that a method can throw. A checked exception must be caught in the method or named in its throws clause. RuntimeException, Error and their subclasses are unchecked and need neither.10 The throws clause makes the exception part of the static type of the method (see Static and dynamic typing). CLU had an earlier form: a procedure listed its exceptions in its specification. An exception that the caller did not handle did not go on up the stack. It became the special exception failure.6 Kotlin has no checked exceptions,11 and C# has no throws clause.

Cleanup and chaining

Cleanup must run on both paths, the normal one and the exceptional one. A finally block runs when control leaves the try block for any reason.212 Other forms tie the cleanup to a resource: with in Python, try-with-resources in Java, using in C#, and destructors in C++, which run during stack unwinding.4 In Java, when close() throws after the body has thrown, the second exception is added to the first as a suppressed exception.12

A handler often raises a second exception that fits its own level, such as a configuration error in place of a parse error. Chaining keeps the first exception as the cause of the second. Python sets __cause__ with raise ... from e, and it sets __context__ when any exception is raised inside an except clause.13 Java and Kotlin pass the cause to the constructor, C# sets InnerException, and JavaScript has the cause option of Error.14

In languages

LanguageVerdictNote
PythonNative
C++Native
JavaNative
CIdiom
C#Native
JavaScriptNative
TypeScriptNative
GoNative
RustIdiom
KotlinNative
SQLAbsentA statement has no handler; a failing statement ends with an error that goes to the host program. Alternative: An EXCEPTION clause in a PL/pgSQL block, or TRY...CATCH in Transact-SQL.
BashIdiom
PowerShellNative
HTMLDoes not applyMarkup does not raise or handle errors.
CSSDoes not applyStyle rules do not raise or handle errors.
Regular expressionsDoes not applyA pattern does not raise or handle errors.

The example files parse three port numbers with the same functions in each language. The table gives the verdict for each tier 1 language.

Language Verdict Form
Python native raise; try with except, else and finally; with
JavaScript native throw of any value; try, catch and finally; the rejection of a promise
TypeScript native as JavaScript; a catch variable has the type unknown or any
Java native throw; try, catch and finally; try-with-resources; checked exceptions
C idiom status codes and errno; setjmp and longjmp for a non-local jump
C++ native throw; try and catch; destructors for cleanup; noexcept
C# native throw; try, catch with when, and finally; using
Go native panic, and recover in a deferred function; error values for ordinary errors
Rust idiom Result<T, E> and the ? operator; panic! for bugs
Kotlin native the exceptions of Java with no checked exceptions; try is an expression
PowerShell native throw; try, catch and finally; trap; non-terminating errors
Bash idiom the exit status; set -e, trap ... ERR and a subshell as the boundary
SQL absent a statement fails with an error that goes to the host program
Regex n/a a pattern does not raise or handle errors
HTML/CSS n/a markup and style rules do not raise or handle errors

Go has panic and recover. A panic stops the function, runs its deferred calls and those of each caller, and ends the program unless a deferred function calls recover.15 The Go FAQ explains why Go has no try statement: the designers think that it makes code convoluted and that it makes programmers treat ordinary errors as exceptional. Ordinary errors are values that a function returns.16 A package can panic inside and recover at its boundary, but its API returns error values.17

Rust has no exceptions. A function that can fail returns Result<T, E>, and panic! is for errors that the program cannot recover from.18 A panic unwinds the stack by default. std::panic::catch_unwind can stop it, but its documentation says that it is not for a general try and catch, and it does not catch a panic that aborts.19

C has no exceptions. A function returns a status code, and some library functions also set errno. No library function sets errno to zero, so a program sets it to zero before the call that it checks.20 setjmp and longjmp give a jump to an earlier point in the call stack, but no cleanup runs, and a local variable that changed after setjmp has an indeterminate value unless it is volatile.21 Koenig and Stroustrup described a portable implementation of C++ exceptions that uses setjmp and longjmp.1

In Bash, each command has an exit status. set -e makes the shell exit when a command fails, except in a few contexts,22 and trap ... ERR runs a command when a command fails.23 A subshell gives a boundary: an exit inside it ends only the subshell, and the outer script tests its status.

SQL statements have no handler. The procedural extensions of some systems add one: an EXCEPTION clause in a PL/pgSQL block,24 and BEGIN TRY ... END TRY BEGIN CATCH ... END CATCH in Transact-SQL.25

PythonGitHub
class ConfigError(Exception):
    pass


def parse_port(text):
    try:
        port = int(text)
    except ValueError as e:
        raise ConfigError(f"not a number: {text}") from e
    if not 1 <= port <= 65535:
        raise ConfigError(f"out of range: {port}")
    return port


checked = 0
for text in ["8080", "70000", "abc"]:
    try:
        print("port", parse_port(text))
    except ConfigError as e:
        cause = type(e.__cause__).__name__ if e.__cause__ else "none"
        print(f"error: {e} (cause: {cause})")
    finally:
        checked += 1
print("checked", checked)
Output
port 8080
error: out of range: 70000 (cause: none)
error: not a number: abc (cause: ValueError)
checked 3
  • Verdict: native. raise raises an exception, and try with except, else and finally handles it.
  • An except clause matches the class of the exception or a base class. A user-defined exception derives from Exception, not from BaseException, so that except Exception does not catch KeyboardInterrupt or SystemExit.
  • raise ... from e sets __cause__. A raise inside an except clause without from sets __context__, so the traceback still shows the first exception.
  • Python code often tries the operation and handles the failure, as int(text) does here, in place of a check before the operation.
  • The with statement and context managers release resources on both paths, like finally. except* handles the parts of an ExceptionGroup.
#include <print>
#include <stdexcept>
#include <string>

struct ConfigError : std::runtime_error {
    using std::runtime_error::runtime_error;
};

struct Counter {
    int& checked;
    ~Counter() { ++checked; }
};

int parse_port(const std::string& text) {
    int port = 0;
    try {
        port = std::stoi(text);
    } catch (const std::invalid_argument&) {
        throw ConfigError("not a number: " + text);
    }
    if (port < 1 || port > 65535) {
        throw ConfigError("out of range: " + std::to_string(port));
    }
    return port;
}

int main() {
    int checked = 0;
    for (const char* text : {"8080", "70000", "abc"}) {
        try {
            Counter counter{checked};
            std::println("port {}", parse_port(text));
        } catch (const ConfigError& e) {
            std::println("error: {}", e.what());
        }
    }
    std::println("checked {}", checked);
}
Output
port 8080
error: out of range: 70000
error: not a number: abc
checked 3
  • Verdict: native. throw throws a value of any copyable type, and a try block with catch handlers catches it by type.
  • C++ has no finally. A local object's destructor runs when the scope ends, also during stack unwinding, so cleanup lives in a destructor. Here Counter counts the values on both paths.
  • Throw by value and catch by const reference. A catch by value copies the object and slices off the part of a derived class.
  • A function declared noexcept must not let an exception escape. If one does, the program calls std::terminate. A destructor is noexcept unless it says otherwise.
  • std::throw_with_nested and std::rethrow_if_nested keep the original exception as a nested exception.
JavaGitHub
import java.util.List;

public class Main {
    static class ConfigException extends Exception {
        ConfigException(String message, Throwable cause) {
            super(message, cause);
        }
    }

    static int parsePort(String text) throws ConfigException {
        int port;
        try {
            port = Integer.parseInt(text);
        } catch (NumberFormatException e) {
            throw new ConfigException("not a number: " + text, e);
        }
        if (port < 1 || port > 65535) {
            throw new ConfigException("out of range: " + port, null);
        }
        return port;
    }

    public static void main(String[] args) {
        int checked = 0;
        for (String text : List.of("8080", "70000", "abc")) {
            try {
                System.out.println("port " + parsePort(text));
            } catch (ConfigException e) {
                Throwable cause = e.getCause();
                String name = cause == null ? "none" : cause.getClass().getSimpleName();
                System.out.println("error: " + e.getMessage() + " (cause: " + name + ")");
            } finally {
                checked++;
            }
        }
        System.out.println("checked " + checked);
    }
}
Output
port 8080
error: out of range: 70000 (cause: none)
error: not a number: abc (cause: NumberFormatException)
checked 3
  • Verdict: native. throw throws a Throwable, and try with catch and finally handles it.
  • ConfigException extends Exception, so it is checked. A call of parsePort must catch it or declare it in a throws clause.
  • NumberFormatException is a subclass of RuntimeException, so it is unchecked.
  • The second argument of the constructor is the cause, which getCause() returns.
  • In try-with-resources, an exception from close() that follows an earlier exception is added to it as a suppressed exception.
#include <errno.h>
#include <setjmp.h>
#include <stdio.h>
#include <stdlib.h>

enum { PORT_OK, NOT_A_NUMBER, OUT_OF_RANGE };

static int parse_port(const char *text, int *out) {
    char *end;
    errno = 0;
    long n = strtol(text, &end, 10);
    if (end == text || *end != '\0') {
        return NOT_A_NUMBER;
    }
    if (errno == ERANGE || n < 1 || n > 65535) {
        return OUT_OF_RANGE;
    }
    *out = (int)n;
    return PORT_OK;
}

static jmp_buf on_error;

static void check(int code) {
    if (code != PORT_OK) {
        longjmp(on_error, code);
    }
}

int main(void) {
    const char *texts[] = {"8080", "70000", "abc"};
    int port;
    for (int i = 0; i < 3; i++) {
        int code = parse_port(texts[i], &port);
        if (code == PORT_OK) {
            printf("port %d\n", port);
        } else {
            printf("error %d: %s\n", code, texts[i]);
        }
    }

    volatile int done = 0;
    switch (setjmp(on_error)) {
    case 0:
        check(parse_port("443", &port));
        done++;
        check(parse_port("abc", &port));
        done++;
        printf("not reached\n");
        break;
    case NOT_A_NUMBER:
        printf("longjmp: not a number after %d\n", done);
        break;
    }
}
Output
port 8080
error 2: 70000
error 1: abc
longjmp: not a number after 1
  • Verdict: idiom. C has no exceptions. A function returns a status code, and the caller tests it.
  • No library function sets errno to zero, so the code does it before strtol.
  • longjmp returns to the point of setjmp from a deeper call. No cleanup runs in the skipped frames.
  • A local variable that changes after setjmp is indeterminate after longjmp unless it is volatile, like done.
int done = 0;
foreach (var text in new[] { "8080", "70000", "abc" })
{
    try
    {
        Console.WriteLine($"port {ParsePort(text)}");
    }
    catch (ConfigException e)
    {
        var cause = e.InnerException?.GetType().Name ?? "none";
        Console.WriteLine($"error: {e.Message} (cause: {cause})");
    }
    finally
    {
        done++;
    }
}
Console.WriteLine($"checked {done}");

static int ParsePort(string text)
{
    int port;
    try
    {
        port = int.Parse(text);
    }
    catch (FormatException e)
    {
        throw new ConfigException($"not a number: {text}", e);
    }
    if (port < 1 || port > 65535)
    {
        throw new ConfigException($"out of range: {port}");
    }
    return port;
}

class ConfigException(string message, Exception? inner = null) : Exception(message, inner);
Output
port 8080
error: out of range: 70000 (cause: none)
error: not a number: abc (cause: FormatException)
checked 3
  • Verdict: native. throw throws an object of a class that derives from System.Exception, and try with catch and finally handles it.
  • C# has no checked exceptions. A method does not declare what it throws.
  • A catch clause can add a filter, catch (IOException e) when (...). The filter runs before the stack unwinds, and when it is false the search goes on.
  • Inside a catch block, throw; throws the exception again and keeps its stack trace. throw e; starts the stack trace again at that point.
  • The second argument of the constructor sets InnerException. using disposes a resource on both paths.
JavaScriptGitHub
class ConfigError extends Error {}

function parsePort(text) {
  let port;
  try {
    port = Number(BigInt(text));
  } catch (err) {
    throw new ConfigError(`not a number: ${text}`, { cause: err });
  }
  if (port < 1 || port > 65535) {
    throw new ConfigError(`out of range: ${port}`);
  }
  return port;
}

let checked = 0;
for (const text of ["8080", "70000", "abc"]) {
  try {
    console.log("port", parsePort(text));
  } catch (e) {
    if (!(e instanceof ConfigError)) throw e;
    const cause = e.cause ? e.cause.constructor.name : "none";
    console.log(`error: ${e.message} (cause: ${cause})`);
  } finally {
    checked++;
  }
}
console.log("checked", checked);
Output
port 8080
error: out of range: 70000 (cause: none)
error: not a number: abc (cause: SyntaxError)
checked 3
  • Verdict: native. throw takes any value, and try with catch and finally handles it.
  • A catch clause has no type test. The handler tests the value with instanceof and throws it again when it does not match.
  • Number("abc") gives NaN and does not throw. BigInt("abc") throws a SyntaxError, so the function uses it to find text that is not an integer.
  • The cause option of the Error constructor stores the original error.
  • An async function returns a promise. Its exception reaches a catch only through await (see Pitfalls on the concept page).
TypeScriptGitHub
class ConfigError extends Error {
  constructor(message: string, options?: ErrorOptions) {
    super(message, options);
    this.name = "ConfigError";
  }
}

function parsePort(text: string): number {
  let port: number;
  try {
    port = Number(BigInt(text));
  } catch (err) {
    throw new ConfigError(`not a number: ${text}`, { cause: err });
  }
  if (port < 1 || port > 65535) {
    throw new ConfigError(`out of range: ${port}`);
  }
  return port;
}

let checked = 0;
for (const text of ["8080", "70000", "abc"]) {
  try {
    console.log("port", parsePort(text));
  } catch (e: unknown) {
    if (!(e instanceof ConfigError)) throw e;
    const cause = e.cause instanceof Error ? e.cause.name : "none";
    console.log(`error: ${e.message} (cause: ${cause})`);
  } finally {
    checked++;
  }
}
console.log("checked", checked);
Output
port 8080
error: out of range: 70000 (cause: none)
error: not a number: abc (cause: SyntaxError)
checked 3
  • Verdict: native. The statements are those of JavaScript, and the type checker adds no rule about exceptions.
  • A function type does not say which exceptions the function can throw. The checker cannot tell the caller that parsePort can fail.
  • Under strict, the variable of a catch clause has the type unknown. The code must narrow it, here with instanceof, before it reads message or cause.
  • The only annotation allowed on a catch variable is unknown or any.
package main

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

var ErrRange = errors.New("out of range")

func parsePort(text string) (int, error) {
	port, err := strconv.Atoi(text)
	if err != nil {
		return 0, fmt.Errorf("not a number: %w", err)
	}
	if port < 1 || port > 65535 {
		return 0, fmt.Errorf("%w: %d", ErrRange, port)
	}
	return port, nil
}

func element(items []int, i int) (n int, err error) {
	defer func() {
		if r := recover(); r != nil {
			err = fmt.Errorf("recovered: %v", r)
		}
	}()
	return items[i], nil
}

func main() {
	for _, text := range []string{"8080", "70000", "abc"} {
		port, err := parsePort(text)
		if err != nil {
			fmt.Printf("error: %v (range: %t)\n", err, errors.Is(err, ErrRange))
			continue
		}
		fmt.Println("port", port)
	}
	_, err := element([]int{1, 2, 3}, 5)
	fmt.Println(err)
}
Output
port 8080
error: out of range: 70000 (range: true)
error: not a number: strconv.Atoi: parsing "abc": invalid syntax (range: false)
recovered: runtime error: index out of range [5] with length 3
  • Verdict: native, for a panic only. A panic runs the deferred calls up the stack and ends the program, unless a deferred function calls recover.
  • Ordinary errors are values of type error, returned as the last result and tested with if err != nil.
  • %w in fmt.Errorf wraps an error, and errors.Is looks through the chain of wrapped errors.
  • An index out of range is a run-time panic. element turns it into an error value.
RustGitHub
use std::fmt;
use std::num::ParseIntError;

#[derive(Debug)]
enum ConfigError {
    NotANumber(ParseIntError),
    OutOfRange(u32),
}

impl fmt::Display for ConfigError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            ConfigError::NotANumber(e) => write!(f, "not a number: {e}"),
            ConfigError::OutOfRange(n) => write!(f, "out of range: {n}"),
        }
    }
}

fn parse_port(text: &str) -> Result<u16, ConfigError> {
    let port: u32 = text.parse().map_err(ConfigError::NotANumber)?;
    if !(1..=65535).contains(&port) {
        return Err(ConfigError::OutOfRange(port));
    }
    Ok(port as u16)
}

fn parse_all(texts: &[&str]) -> Result<Vec<u16>, ConfigError> {
    let mut ports = Vec::new();
    for text in texts {
        ports.push(parse_port(text)?);
    }
    Ok(ports)
}

fn main() {
    for text in ["8080", "70000", "abc"] {
        match parse_port(text) {
            Ok(port) => println!("port {port}"),
            Err(e) => println!("error: {e}"),
        }
    }
    println!("{:?}", parse_all(&["80", "443"]));
    println!("{:?}", parse_all(&["80", "x", "443"]).map_err(|e| e.to_string()));
}
Output
port 8080
error: out of range: 70000
error: not a number: invalid digit found in string
Ok([80, 443])
Err("not a number: invalid digit found in string")
  • Verdict: idiom. Rust has no exceptions. A function that can fail returns Result<T, E>, and ? returns the error to the caller.
  • The type of each function shows that it can fail, and the compiler warns when a Result is not used.
  • panic! is for bugs. By default it unwinds the stack and drops the values of each frame. With panic = "abort" in the Cargo profile, it ends the process at once.
  • std::panic::catch_unwind can stop an unwinding panic, but its documentation says not to use it as a general try and catch.
KotlinGitHub
class ConfigException(message: String, cause: Throwable? = null) : Exception(message, cause)

fun parsePort(text: String): Int {
    val port = try {
        text.toInt()
    } catch (e: NumberFormatException) {
        throw ConfigException("not a number: $text", e)
    }
    if (port !in 1..65535) throw ConfigException("out of range: $port")
    return port
}

fun main() {
    var checked = 0
    for (text in listOf("8080", "70000", "abc")) {
        try {
            println("port ${parsePort(text)}")
        } catch (e: ConfigException) {
            println("error: ${e.message} (cause: ${e.cause?.javaClass?.simpleName ?: "none"})")
        } finally {
            checked++
        }
    }
    println("checked $checked")
}
Output
port 8080
error: out of range: 70000 (cause: none)
error: not a number: abc (cause: NumberFormatException)
checked 3
  • Verdict: native. The exception classes are those of Java, and throw and try with catch and finally work in the same way.
  • Kotlin has no checked exceptions. parsePort throws a subclass of Exception but needs no declaration. @Throws adds the declaration for Java callers.
  • try is an expression. Its value is the last expression of the try block or of the catch block that ran.
  • throw is an expression of type Nothing, so it can stand where a value is expected.
  • runCatching returns a Result in place of an exception, for code that prefers values.
BashGitHub
parse_port() {
  local text=$1
  if [[ ! $text =~ ^[0-9]+$ ]]; then
    return 2
  fi
  if (( text < 1 || text > 65535 )); then
    return 3
  fi
  echo "$text"
}

for text in 8080 70000 abc; do
  if port=$(parse_port "$text"); then
    echo "port $port"
  else
    echo "error: status $? for $text"
  fi
done

(
  set -e
  trap 'echo "trap ERR: status $?"' ERR
  parse_port abc > /dev/null
  echo "not reached"
)
echo "subshell status $?"
Output
port 8080
error: status 3 for 70000
error: status 2 for abc
trap ERR: status 2
subshell status 2
  • Verdict: idiom. Bash has no exceptions. Each command ends with an exit status, 0 for success, and if, && and || test it.
  • A function returns a status with return. Its value comes back on standard output, here through command substitution.
  • set -e ends the shell when a command fails, and trap ... ERR runs a command first. A subshell ( ... ) limits the exit to the subshell, so the outer script can test its status like a handler.
  • set -e has no effect on a command that is the test of an if, part of a && or || list, or not the last command of a pipeline (see Pitfalls on the concept page).
  • trap ... EXIT runs cleanup when the shell exits on any path.
PowerShellGitHub
class ConfigException : System.Exception {
    ConfigException([string] $message, [System.Exception] $inner) : base($message, $inner) {}
}

function ConvertTo-Port([string] $Text) {
    try {
        $port = [int]::Parse($Text)
    } catch [System.FormatException] {
        throw [ConfigException]::new("not a number: $Text", $_.Exception)
    }
    if ($port -lt 1 -or $port -gt 65535) {
        throw [ConfigException]::new("out of range: $port", $null)
    }
    $port
}

$checked = 0
foreach ($text in '8080', '70000', 'abc') {
    try {
        "port $(ConvertTo-Port $text)"
    } catch [ConfigException] {
        $inner = $_.Exception.InnerException
        $cause = if ($inner) { $inner.GetType().Name } else { 'none' }
        "error: $($_.Exception.Message) (cause: $cause)"
    } finally {
        $checked++
    }
}
"checked $checked"
Output
port 8080
error: out of range: 70000 (cause: none)
error: not a number: abc (cause: FormatException)
checked 3
  • Verdict: native. throw makes a terminating error, and try with typed catch blocks and finally handles it. A trap statement is another kind of handler, for a whole scope.
  • In a catch block, $_ is an ErrorRecord. Its Exception property holds the .NET exception.
  • [int]::Parse is a .NET method, so it throws FormatException, and the catch block can match its type.
  • Most cmdlet errors are non-terminating. They go to the error stream and do not reach catch, unless -ErrorAction Stop turns them into terminating errors (see Pitfalls on the concept page).
  • Error values and result types. Go, Rust and C return the error as a value. The caller must test it at each call, and the type or the signature shows that the call can fail. Rust's ? operator returns the error to the caller in one character, which gives explicit propagation with little text.
  • Panics. Go and Rust keep a mechanism that unwinds the stack for bugs and states that the program cannot recover from, and they use error values for the rest.1618
  • Exception groups. Concurrent code can fail in several places at once. Python has ExceptionGroup and except*, which handles the matching parts of a group and raises the rest again.26 JavaScript has AggregateError, and Promise.any rejects with one when all its promises are rejected.27
  • Exceptions in asynchronous code. An exception in an async function goes into the promise or task that the function returns. It reaches a handler only when the caller waits for the result (see Async/await and Pitfalls).285
  • Exceptions as control flow. A Python iterator signals that it has no more items by raising StopIteration (see Iterator).13 CLU programs also used exceptions to pass ordinary information to the caller.6
  • Exceptions and recursion. One raise can leave many frames of a deep recursion at once, so a recursive search can stop when it finds an answer (see Recursion).
  • Memory and other resources. In a language with Garbage collection, the frames that the unwinder removes leave their objects for the collector. A file or a lock that those frames held needs finally, with or using, because the collector can run much later.

Pitfalls

A broad handler hides a bug

A handler for Exception catches every error, also the ones that come from bugs. Here the key "prot" has a typing error. The handler was written for text that is not a number, but it catches the KeyError and returns the default.

This code runs but gives a wrong answer on purpose.

config = {"port": "8080"}


def port_of(config):
    try:
        return int(config["prot"])
    except Exception:
        return 80


print(port_of(config))
Output
80

The fix is to catch only the exception that the handler can deal with, and to keep the try block small. Now the typing error stops the program with KeyError at the line that has it.

This code raises KeyError, on purpose.

config = {"port": "8080"}


def port_of(config):
    text = config["prot"]
    try:
        return int(text)
    except ValueError:
        return 80


print(port_of(config))

An except clause with no expression is worse. It matches every exception,2 also KeyboardInterrupt and SystemExit, which derive from BaseException and not from Exception.13

A return in finally discards the exception

When a finally block ends with return, break or continue, the exception that was passing through is lost.2 In Java the rule is the same: when the finally block completes abruptly, the try statement completes for the same reason, and the exception is discarded.12

This code runs but gives a wrong answer on purpose.

def save():
    try:
        raise OSError("disk full")
    finally:
        return "saved"


print(save())
Output
saved

The caller sees saved, and the error is gone. PEP 765 found that most of these statements in real code were bugs.29 The same PEP made the compiler warn about them with a SyntaxWarning.30 The fix is to put the return after the try statement, so that finally only cleans up.

A second exception without the first one

When a handler throws a second exception and does not pass the first one as the cause, the reason for the failure is lost. Java does not chain the exceptions by itself.

This code runs but gives a wrong answer on purpose.

public class Main {
    static int parsePort(String text) {
        try {
            return Integer.parseInt(text);
        } catch (NumberFormatException e) {
            throw new IllegalArgumentException("bad port");
        }
    }

    public static void main(String[] args) {
        try {
            parsePort("80a");
        } catch (IllegalArgumentException e) {
            System.out.println(e.getMessage() + ", cause: " + e.getCause());
        }
    }
}
Output
bad port, cause: null

The fix is new IllegalArgumentException("bad port", e), as in the Java example. In C#, throw e; in a handler has a related effect: it starts the stack trace again at that point. throw; keeps the original trace.531

A destructor that throws during unwinding

C++ runs destructors during stack unwinding. If a destructor throws while another exception is passing through, the program calls std::terminate.132 A destructor with no noexcept specifier is noexcept unless the destructor of a member or a base can throw, and an exception that leaves a noexcept function also calls std::terminate.33 This destructor says noexcept(false), so it compiles, and it throws during unwinding.

This code fails on purpose. The output below is the error.

#include <print>
#include <stdexcept>

struct Connection {
    ~Connection() noexcept(false) { throw std::runtime_error("close failed"); }
};

void send() {
    Connection connection;
    throw std::runtime_error("send failed");
}

int main() {
    try {
        send();
    } catch (const std::exception& e) {
        std::println("caught: {}", e.what());
    }
}

The program aborts, and the handler in main does not run. The fix is a destructor that does not throw. A failure on close can be reported through a separate close() function that the caller calls on the normal path.

An async call that nobody waits for

An exception in an async function rejects the promise that the function returns.28 The call does not throw, so a try statement around it does not see the exception. Node.js treats a rejection with no handler as an uncaught exception by default,34 and an uncaught exception ends the process with status 1.35

This code fails on purpose. The output below is the error.

async function load() {
  throw new Error("disk full");
}

try {
  load();
} catch (e) {
  console.log("caught", e.message);
}
console.log("after the call");

The fix is await, which turns the rejection back into an exception at the point of the call.

async function load() {
  throw new Error("disk full");
}

async function main() {
  try {
    await load();
  } catch (e) {
    console.log("caught", e.message);
  }
}

main();
Output
caught disk full

A PowerShell error that does not reach catch

Most cmdlet errors are non-terminating. The cmdlet writes the error and goes on, and a non-terminating error does not trigger catch or trap.36

This code runs but gives a wrong answer on purpose.

try {
    Get-Item -Path ./no-such-file
    'after Get-Item'
} catch {
    'caught'
}
Output
after Get-Item

The fix is -ErrorAction Stop, which makes the error terminating, so the catch block runs.3637

try {
    Get-Item -Path ./no-such-file -ErrorAction Stop
    'after Get-Item'
} catch {
    'caught'
}
Output
caught

set -e has no effect inside a tested function

Bash ignores set -e in the test of an if, in a && or || list, and in a function that runs in such a context, with all the commands of that function.22 So the error in deploy does not stop it.

This code runs but gives a wrong answer on purpose.

set -e

deploy() {
  false
  echo "deploy went on after the failure"
}

if deploy; then
  echo "deploy succeeded"
fi
Output
deploy went on after the failure
deploy succeeded

The fix is to test each command that can fail and return its status, as in false || return.

deploy() {
  false || return
  echo "not reached"
}

if deploy; then
  echo "deploy succeeded"
else
  echo "deploy failed with status $?"
fi
Output
deploy failed with status 1

Cost

  • The normal path. A table-based implementation adds no instructions where no exception is thrown. The compiler writes tables that map code addresses to cleanup code and handlers. The tables use space, and the unwinder reads them only when an exception is thrown.19
  • The throw. A throw searches the tables, unwinds each frame and runs its cleanup code, so it costs much more than a return. Koenig and Stroustrup saw this as an advantage, because it discourages exceptions where other control structures will do.1 .NET adds Try methods such as Int32.TryParse, which return a Boolean in place of an exception, for code where the cost of exceptions is too high.31
  • Python. CPython 3.11 made try statements "zero-cost": a try costs nothing when no exception is raised.38
  • Error values. A Result or an error value is a value that the caller tests after each call. The test is a branch on the normal path, and the value can make the return type larger.

History

  • 1975. John B. Goodenough published "Exception Handling: Issues and a Proposed Notation" in Communications of the ACM.39
  • 1975 to 1979. Barbara Liskov's group designed the exception mechanism of CLU. They made the main decisions by June 1975 and completed the design in 1977. CLU used the termination model and turned unhandled exceptions into failure.6 Liskov and Alan Snyder described the mechanism in 1979.40
  • 1989 and 1990. Andrew Koenig and Bjarne Stroustrup presented the design of exception handling for C++: termination, handlers that match by type, destructors during unwinding, and an implementation with no run-time cost until a throw.1
  • 2022. Python 3.11 added exception groups and except*.2638

References

  1. Andrew Koenig and Bjarne Stroustrup, Exception Handling for C++ (revised), Proceedings of the USENIX C++ Conference, 1990, 1 Introduction; 5.2 Throwing Exceptions in Destructors; 7 Termination vs. Resumption; 16.5 Outline of an Efficient Implementation
  2. The Python Language Reference, Compound statements, Python 3.14, 8.4 The try statement: 8.4.1 except clause, 8.4.4 finally clause
  3. Working Draft, Programming Languages, C++ (N4950, the C++23 draft), [except.handle], paragraphs 6 and 9
  4. Working Draft, Programming Languages, C++ (N4950, the C++23 draft), [except.ctor], paragraphs 1 and 2
  5. C# language reference, Exception-handling statements, The throw statement; The try-catch statement; A when exception filter
  6. Barbara Liskov, A History of CLU, HOPL-II, 1993, 3.9 Exception Handling
  7. Common Lisp HyperSpec, 9.1.4 Signaling and Handling Conditions
  8. Common Lisp HyperSpec, 9.1.4.2 Restarts
  9. Itanium C++ ABI: Exception Handling, 1.1 Exception Handler Framework; 1.6 Personality Routine
  10. The Java Language Specification, Java SE 25 Edition, 11.1.1 The Kinds of Exceptions; 11.2.3 Exception Checking
  11. Kotlin documentation, Exceptions, the introduction; Exception interoperability with Java, Swift, and Objective-C
  12. The Java Language Specification, Java SE 25 Edition, 14.20.2 Execution of try-finally and try-catch-finally; 14.20.3.1 Basic try-with-resources
  13. The Python Standard Library, Built-in Exceptions, Python 3.14, Exception context; Base classes, BaseException; Concrete exceptions, StopIteration; Exception hierarchy
  14. ECMA-262, ECMAScript 2026 Language Specification, 20.5.8.1 InstallErrorCause
  15. The Go Programming Language Specification, Handling panics; Run-time panics
  16. Go FAQ, Why does Go not have exceptions?
  17. Andrew Gerrand, Defer, Panic, and Recover, The Go Blog, 2010, the text on recover, and the encoding/json example
  18. The Rust Programming Language, Chapter 9, Error Handling, the introduction of chapter 9
  19. The Rust Standard Library, Function catch_unwind, the description and Notes
  20. N3220, ISO/IEC 9899:2024 working draft (C23), 7.5 Errors <errno.h>, paragraph 3
  21. N3220, ISO/IEC 9899:2024 working draft (C23), 7.13.1.1 The setjmp macro, paragraph 4; 7.13.2.1 The longjmp function, paragraphs 2 and 3
  22. Bash Reference Manual, 4.3.1 The Set Builtin, the -e option
  23. Bash Reference Manual, 4.1 Bourne Shell Builtins, trap
  24. PostgreSQL documentation, PL/pgSQL Control Structures, Trapping Errors
  25. Transact-SQL reference, TRY...CATCH, the description
  26. PEP 654: Exception Groups and except*, Specification
  27. ECMA-262, ECMAScript 2026 Language Specification, 27.2.4.3 Promise.any
  28. ECMA-262, ECMAScript 2026 Language Specification, 27.7.5.2 AsyncBlockStart
  29. PEP 765: Disallow return/break/continue that exit a finally block, Rationale
  30. What's new in Python 3.14, PEP 765: Control flow in finally blocks
  31. .NET documentation, Best practices for exceptions, Call Try* methods to avoid exceptions; Capture and rethrow exceptions properly
  32. Working Draft, Programming Languages, C++ (N4950, the C++23 draft), [except.terminate], paragraph 1
  33. Working Draft, Programming Languages, C++ (N4950, the C++23 draft), [except.spec], paragraphs 5 and 8
  34. Node.js documentation, Command-line API, --unhandled-rejections=mode
  35. Node.js documentation, Process, Event: 'uncaughtException'
  36. PowerShell documentation, about_Error_Handling, Types of errors, Non-terminating errors; Script-terminating errors
  37. PowerShell documentation, about_Try_Catch_Finally, Long description; Catching errors
  38. What's New In Python 3.11, Faster CPython, Misc
  39. John B. Goodenough, Exception Handling: Issues and a Proposed Notation, Communications of the ACM 18(12), 1975, pages 683 to 696
  40. Barbara Liskov and Alan Snyder, Exception Handling in CLU, IEEE Transactions on Software Engineering SE-5(6), 1979, pages 546 to 558

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