Conceptcore
Panic
Also called panic, abort, fail-fast, unrecoverable error, fatal error.
A panic is how a program reacts to a bug that it finds while it runs. It stops the current work, and either ends the process or lets a boundary throw the broken work away.
- Applies to
- core-languages
Idea
Some failures are expected. A file is missing, or a user types a letter where a number should be. A program handles these with Error value or with Exception. Other failures are bugs. An index is past the end of an array, or a value breaks an invariant that the code relies on. The program is now in a state that its author did not plan for. Code that goes on from that state can give wrong answers or damage data.
A panic is the reaction to such a bug. The program stops the current work at once. It does not try to repair the state. Jim Gray called this property fail-fast: a module "should either function correctly or it should detect the fault, signal failure and stop operating."1 The failure is then handled at a coarser level. The whole process ends, or a boundary such as a thread, a request handler or a worker throws the broken work away and goes on with the next one.
In Rust, a failed assert! panics. Here each call runs in its own thread, so the panic ends that thread and not the program.
use std::panic;
use std::thread;
fn average(values: &[i32]) -> i32 {
assert!(!values.is_empty(), "average of no values");
values.iter().sum::<i32>() / values.len() as i32
}
fn main() {
panic::set_hook(Box::new(|_| {}));
for values in [vec![2, 4, 9], vec![]] {
let worker = thread::spawn(move || average(&values));
match worker.join() {
Ok(avg) => println!("average {avg}"),
Err(_) => println!("the worker panicked; main goes on"),
}
}
}
average 5
the worker panicked; main goes on
The call panic::set_hook replaces the default report on standard error with nothing, so the output stays short.
How it works
A panic has four steps.
- Detection. A check fails. The check is explicit, such as
assert!orpanic!, or the language inserts it, such as the bounds check on an index. In Go, an index out of bounds causes a run-time panic, which is the same as a call ofpanicwith a value of typeruntime.Error.2 At the level of the machine, an inserted check is a comparison and a branch to a rarely used path that starts the panic. - Report. The runtime records what went wrong. Go reports the value given to
panic.3 In Rust, the panic hook runs first, before the stack unwinds or the process aborts, and the default hook prints a message to standard error.4 - Unwinding or abort. The runtime either walks back up the stack or ends the process at once. The next section compares the two.
- Stop at a boundary, or end. If some frame on the stack catches the panic, execution goes on there. If none does, the process ends.
Unwinding and abort
Unwinding means that the runtime walks back up the stack and cleans up the data of each function that it leaves.5 In Go, the deferred functions of each frame run, from the function that panicked up to the top function of the goroutine.3 In Rust, unwinding runs destructors but no other code.6 In C++, stack unwinding destroys the local objects between the throw and the handler, in the reverse order of their construction (Exception).7
Abort means that the process ends at once, without that cleanup. The operating system then frees the memory of the process.5 Rust can be set up to abort on a panic. The line panic = 'abort' in a [profile] section of Cargo.toml selects it, for example for release builds.5 The function std::process::abort ends the process in the same way, and no destructors run on any thread.8 C abort ends the program by raise(SIGABRT). Whether it flushes the open streams is up to the implementation.9
| Unwinding | Abort | |
|---|---|---|
| Cleanup code | runs: destructors, deferred calls, finally |
does not run |
| Can a boundary catch it? | yes | no |
| Buffered output and files | flushed by the cleanup code | may be lost |
| Binary | larger; it holds the data that the unwinder needs | smaller5 |
| State after the failure | the cleanup code runs on state that may be broken | nothing runs on the broken state |
The last row is the main tradeoff. Unwinding gives the program a chance to close files and release locks. It also runs code in a process that has just shown a bug.
Boundaries
A boundary is the place where a panic stops and becomes an ordinary failure. The Rust 1.9 announcement says that panics abort execution up to an "isolation boundary", and code on the other side can still run. "A server, for example, does not necessarily need to go down just because of an assertion failure in one of its threads."6
- A thread. In Rust,
JoinHandle::joinreturnsErrwhen the thread panicked.10 The idea example uses this. - A call. Rust
catch_unwindruns a closure and returnsErrif the closure panics and unwinds.11 Gorecoverstops a panic when a deferred function calls it directly. The function that deferred it then returns to its caller in the normal way.3 - A process. An operating system process shares no memory with other processes. Gray's fail-fast processes share no state and talk only by messages, so a failed process can stop without harm to the others.1 Joe Armstrong built the error handling of Erlang on the same idea: "Let some other process do the error recovery" and "If you can't do what you want to do, die."12
A boundary is safe only if the work that failed did not change shared state. A thread or a process that owns its data can stop and leave nothing broken behind. A call that changed a shared map halfway cannot. The first pitfall below shows this.
Stop or recover
The question is whether the program can trust its own state.
- Recover from expected failures. A missing file, a timeout or bad input from a user is part of normal operation. The Rust book says to use
Resultfor these.13 Go says the same, and keepspanicandrecoverfor "truly exceptional conditions".14 - Stop on bugs. The Rust book says to panic when the code could end up in a bad state: an assumption, a guarantee, a contract or an invariant is broken, and the code after that point relies on not being in the bad state.13 Java says that an
Errorindicates "serious problems that a reasonable application should not try to catch".15 - Recover at a coarse boundary only. When a server must stay up, it catches the panic at the edge of a request or a worker, logs it, and throws away all the state of that unit. It does not catch a panic in the middle of an operation and go on.
- Stop the whole process when the state is shared. If the bug may have damaged state that other work uses, the process ends. A supervisor, a service manager or a person then starts it again from a clean state.
In languages
| Language | Verdict | Note |
|---|---|---|
| Python | Idiom | |
| C++ | Idiom | |
| Java | Idiom | |
| C | Idiom | |
| C# | Idiom | |
| JavaScript | Idiom | |
| TypeScript | Idiom | |
| Go | Native | |
| Rust | Native | |
| Kotlin | Idiom | Kotlin on the JVM uses the exceptions of Java, with the same split between Error and Exception; no example file because kotlinc is not installed on the machine that recorded the examples. Alternative: Catch Exception at a boundary and let an Error end the program, as in the Java example. |
| SQL | Absent | A statement fails and the engine reports the failure to the host program; it does not stop the host program. Alternative: The error handling of the host language. |
| Bash | Idiom | The builtin exit ends the shell with a status, and set -e stops the script at the first command that fails. Alternative: A trap on EXIT for cleanup. |
| PowerShell | Idiom | A script stops with the keyword exit or with a terminating error; no example file because pwsh is not installed on the machine that recorded the examples. Alternative: Try and catch at the boundary of each unit of work. |
| HTML | Does not apply | Markup does not run code. |
| CSS | Does not apply | Style rules do not run code. |
| Regular expressions | Does not apply | A pattern has no notion of a bug. |
The example files run three jobs. One job has a bug, an index out of range. A boundary catches the failure, the cleanup of that job runs, and the next job goes on. Each file then shows the hard stop of the language in a fails block.
| Language | Verdict | Form |
|---|---|---|
| Python | idiom | no panic; a bug raises an exception; sys.exit raises SystemExit; os._exit and os.abort stop at once |
| JavaScript | idiom | no panic; a bug throws; process.exit and process.abort in Node.js |
| TypeScript | idiom | as JavaScript; the return type never marks a function that does not return |
| Java | idiom | Error versus Exception; System.exit and Runtime.halt |
| C | idiom | abort, exit and assert; no unwinding |
| C++ | idiom | std::terminate and std::abort; noexcept |
| C# | idiom | no panic; a bug throws; Environment.FailFast |
| Go | native | panic, recover in a deferred function, run-time panics |
| Rust | native | panic!, unwinding or abort, catch_unwind, join |
| Kotlin | idiom | the exceptions of the JVM, with the same split of Error and Exception as Java |
| PowerShell | idiom | the keyword exit and terminating errors |
| Bash | idiom | the builtin exit, and set -e to stop at the first failing command |
| SQL | absent | a statement fails; the engine does not panic the host program |
| Regex | n/a | a pattern has no notion of a bug |
| HTML/CSS | n/a | markup and style rules do not run code |
Go and Rust have a separate mechanism for bugs. In the other languages, a bug and an expected failure use the same exception mechanism, and the split is a convention or a type hierarchy. Java puts it in the type hierarchy: an Exception is a condition that "a reasonable application might want to catch",16 and an Error is one that it should not try to catch.15 Python puts SystemExit under BaseException, not under Exception, so that code which catches Exception does not catch it by accident.17
Each language also has a hard stop that skips the cleanup code.
- C.
exitcalls the functions registered withatexitin the reverse order of registration, and then flushes and closes the open streams.abortends the program abnormally.9 A failedassertwrites a message to standard error and callsabort.9 - C++.
vector::atchecks the index and throwsstd::out_of_range. The standard givesoperator[]no such clause.18 In some situations the language abandons exception handling and callsstd::terminate. One is an exception that no handler catches. Another is an exception that reaches the end of anoexceptfunction.19 The default terminate handler callsabort.20 - Java.
System.exitstarts the shutdown sequence, which runs the shutdown hooks.Runtime.haltends the JVM without that sequence. When the JVM ends, threads stop running Java code at once, so theirfinallyblocks do not run.21 - C#.
Environment.FailFast"Immediately terminates the process". On Unix systems it writes the message and a stack trace to standard error, and thefinallyblocks do not run.22 - Python.
sys.exitraisesSystemExit, sofinallyblocks run and an outer handler can stop the exit.23os._exitends the process without the cleanup handlers and without flushing the standard I/O buffers.24 - Node.js.
process.exitends the process synchronously, and an exception that nothing catches ends it with exit code 1.25 In TypeScript, the return typeneversays that a function throws an exception or ends the program.26
import sys
def run_job(job, items):
try:
return items[job] * 10
finally:
print("cleanup job", job)
items = [1, 2]
for job in [0, 5, 1]:
try:
print("job", job, "->", run_job(job, items))
except Exception as exc:
print("job", job, "failed:", type(exc).__name__, exc)
try:
sys.exit(3)
except Exception:
print("not reached: SystemExit is not an Exception")
except BaseException as exc:
print("caught", type(exc).__name__, "with code", exc.code)
cleanup job 0
job 0 -> 10
cleanup job 5
job 5 failed: IndexError list index out of range
cleanup job 1
job 1 -> 20
caught SystemExit with code 3
- Verdict: idiom. Python has no panic. A bug such as an index out of range raises an ordinary exception, here
IndexError, and a boundary catches it like any other. sys.exitraisesSystemExit. It inherits fromBaseException, not fromException, so a handler forExceptiondoes not stop the exit.finallyblocks still run on the way out.os._exitandos.abortare the hard stops. They end the process without thefinallyblocks.
os._exit ends the process with the given status. It runs no cleanup handlers and does not flush the standard I/O buffers, so the finally block below never prints.
This code fails on purpose. The output below is the error.
import os
try:
os._exit(3)
finally:
print("cleanup")
A bare except: catches every exception, SystemExit too. The program below asks to stop, and the handler keeps it alive.
This code runs but gives a wrong answer on purpose.
import sys
for attempt in range(3):
try:
print("attempt", attempt)
sys.exit(1)
except:
print("swallowed the exit")
print("still running")
attempt 0
swallowed the exit
attempt 1
swallowed the exit
attempt 2
swallowed the exit
still running
#include <iostream>
#include <stdexcept>
#include <vector>
struct Cleanup {
int job;
~Cleanup() { std::cout << "cleanup job " << job << '\n'; }
};
int run_job(int job, const std::vector<int>& items) {
Cleanup guard{job};
return items.at(job) * 10;
}
int main() {
std::vector<int> items{1, 2};
for (int job : {0, 5, 1}) {
try {
int result = run_job(job, items);
std::cout << "job " << job << " -> " << result << '\n';
} catch (const std::out_of_range&) {
std::cout << "job " << job << " failed: out_of_range\n";
}
}
}
cleanup job 0
job 0 -> 10
cleanup job 5
job 5 failed: out_of_range
cleanup job 1
job 1 -> 20
- Verdict: idiom. C++ has no panic.
vector::atchecks the index and throwsstd::out_of_range, and the destructor ofguardruns while the stack unwinds. vector::operator[]does not check the index. The standard givesata Throws clause and givesoperator[]none. A bad index there reads memory outside the vector, and no handler can catch that.std::terminateis the hard stop of the exception system. Its default handler callsstd::abort.
An exception that leaves a noexcept function calls std::terminate. No handler outside the function gets a chance to run.
This code fails on purpose. The output below is the error.
#include <iostream>
#include <stdexcept>
#include <vector>
int run_job(int job, const std::vector<int>& items) noexcept {
return items.at(job) * 10;
}
int main() {
std::vector<int> items{1, 2};
try {
std::cout << run_job(5, items) << '\n';
} catch (const std::exception&) {
std::cout << "caught\n";
}
}
With operator[], the same bad index reads memory outside the vector. AddressSanitizer reports it.
This code has a memory error, on purpose, and the sanitizer reports it.
#include <iostream>
#include <vector>
int main() {
std::vector<int> items{1, 2};
std::cout << items[5] * 10 << '\n';
}
public class Main {
static int runJob(int job, int[] items) {
try {
return items[job] * 10;
} finally {
System.out.println("cleanup job " + job);
}
}
public static void main(String[] args) {
int[] items = {1, 2};
for (int job : new int[] {0, 5, 1}) {
try {
System.out.println("job " + job + " -> " + runJob(job, items));
} catch (Exception e) {
System.out.println("job " + job + " failed: " + e);
}
}
Throwable bug = new AssertionError("broken invariant");
System.out.println("AssertionError is an Exception: " + (bug instanceof Exception));
System.out.println("AssertionError is an Error: " + (bug instanceof Error));
}
}
cleanup job 0
job 0 -> 10
cleanup job 5
job 5 failed: java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 2
cleanup job 1
job 1 -> 20
AssertionError is an Exception: false
AssertionError is an Error: true
- Verdict: idiom. Java has no panic, but it splits
Throwablein two. AnExceptionis a condition that a reasonable application might want to catch. AnErroris a serious problem that it should not try to catch. ArrayIndexOutOfBoundsExceptionis aRuntimeException, so the boundary above catches it.AssertionError,OutOfMemoryErrorandStackOverflowErrorare subclasses ofError.System.exitstarts the shutdown sequence and runs the shutdown hooks.Runtime.haltends the JVM at once, without the hooks.
A handler for Exception does not catch an Error. The AssertionError passes the boundary and ends the program.
This code raises AssertionError, on purpose.
public class Main {
static void runJob(int job) {
if (job < 0) {
throw new AssertionError("negative job " + job);
}
System.out.println("job " + job + " done");
}
public static void main(String[] args) {
for (int job : new int[] {1, -1, 2}) {
try {
runJob(job);
} catch (Exception e) {
System.out.println("job " + job + " failed: " + e);
}
}
}
}
When the JVM halts, the threads stop running Java code. The finally block does not run.
This code fails on purpose. The output below is the error.
public class Main {
public static void main(String[] args) {
Runtime.getRuntime().addShutdownHook(new Thread(() -> System.out.println("shutdown hook")));
try {
Runtime.getRuntime().halt(3);
} finally {
System.out.println("cleanup");
}
}
}
#include <stdio.h>
#include <stdlib.h>
static void close_log(void) { puts("atexit: close log"); }
static void flush_cache(void) { puts("atexit: flush cache"); }
static void stop(int status) {
puts("stopping");
exit(status);
}
int main(void) {
atexit(close_log);
atexit(flush_cache);
stop(EXIT_SUCCESS);
puts("not reached");
}
stopping
atexit: flush cache
atexit: close log
- Verdict: idiom. C has no panic and no unwinding. A program stops with
exitor withabort. exitcalls the functions registered withatexitin the reverse order of registration. It then flushes and closes the open streams.abortraisesSIGABRT. It does not run theatexitfunctions, and the standard leaves it to the implementation whether it flushes the streams. A failedassertcallsabort.
abort ends the program without the atexit functions.
This code fails on purpose. The output below is the error.
#include <stdio.h>
#include <stdlib.h>
static void close_log(void) { puts("atexit: close log"); }
int main(void) {
atexit(close_log);
fputs("broken invariant\n", stderr);
abort();
}
A failed assert writes the expression, the file and the line to standard error, then calls abort.
This code fails on purpose. The output below is the error.
#include <assert.h>
#include <stddef.h>
static int item(const int *items, size_t len, size_t i) {
assert(i < len);
return items[i];
}
int main(void) {
int items[] = {1, 2};
return item(items, 2, 5);
}
using System;
static int RunJob(int job, int[] items)
{
try
{
return items[job] * 10;
}
finally
{
Console.WriteLine($"cleanup job {job}");
}
}
int[] items = [1, 2];
foreach (int job in new[] { 0, 5, 1 })
{
try
{
Console.WriteLine($"job {job} -> {RunJob(job, items)}");
}
catch (IndexOutOfRangeException e)
{
Console.WriteLine($"job {job} failed: {e.GetType().Name}");
}
}
cleanup job 0
job 0 -> 10
cleanup job 5
job 5 failed: IndexOutOfRangeException
cleanup job 1
job 1 -> 20
- Verdict: idiom. C# has no panic. A bug such as an index out of range throws an ordinary exception, and a boundary catches it.
Environment.FailFastis the hard stop. It ends the process at once and writes the message and a stack trace.
Environment.FailFast ends the process before the finally block can run.
This code fails on purpose. The output below is the error.
using System;
try
{
Environment.FailFast("broken invariant");
}
finally
{
Console.WriteLine("cleanup");
}
function runJob(job, items) {
try {
return items[job].value * 10;
} finally {
console.log("cleanup job", job);
}
}
const items = [{ value: 1 }, { value: 2 }];
for (const job of [0, 5, 1]) {
try {
console.log("job", job, "->", runJob(job, items));
} catch (err) {
console.log("job", job, "failed:", err instanceof TypeError, err.message);
}
}
cleanup job 0
job 0 -> 10
cleanup job 5
job 5 failed: true Cannot read properties of undefined (reading 'value')
cleanup job 1
job 1 -> 20
- Verdict: idiom. JavaScript has no panic. A bug raises an ordinary exception, here a
TypeErrorfrom reading a property ofundefined, and a boundary catches it. - An exception that no code catches ends a Node.js process with exit code 1.
process.exitandprocess.abortare the hard stops in Node.js.
process.exit ends the process synchronously. The finally block does not run.
This code fails on purpose. The output below is the error.
try {
process.exit(3);
} finally {
console.log("cleanup");
}
function fail(message: string): never {
throw new Error("invariant broken: " + message);
}
function runJob(job: number, items: readonly number[]): number {
try {
const item = items[job] ?? fail(`no item ${job}`);
return item * 10;
} finally {
console.log("cleanup job", job);
}
}
const items = [1, 2] as const;
for (const job of [0, 5, 1]) {
try {
console.log("job", job, "->", runJob(job, items));
} catch (err) {
console.log("job", job, "failed:", (err as Error).message);
}
}
cleanup job 0
job 0 -> 10
cleanup job 5
job 5 failed: invariant broken: no item 5
cleanup job 1
job 1 -> 20
- Verdict: idiom. TypeScript runs as JavaScript and has no panic. A bug is an ordinary exception.
- The return type
nevermarks a function that does not return. The checker then treatsitems[job] ?? fail(...)as anumber. - In Node.js,
process.exitis the hard stop, as in JavaScript.
process.exit ends the process before the finally block can run.
This code fails on purpose. The output below is the error.
function stop(code: number): never {
process.exit(code);
}
try {
stop(3);
} finally {
console.log("cleanup");
}
package main
import (
"fmt"
"runtime"
)
func runJob(job int, items []int) (result int, err error) {
defer fmt.Println("cleanup job", job)
defer func() {
if r := recover(); r != nil {
_, isRuntime := r.(runtime.Error)
err = fmt.Errorf("recovered (runtime error: %v): %v", isRuntime, r)
}
}()
return items[job] * 10, nil
}
func main() {
items := []int{1, 2}
for _, job := range []int{0, 5, 1} {
result, err := runJob(job, items)
if err != nil {
fmt.Println("job", job, "failed:", err)
continue
}
fmt.Println("job", job, "->", result)
}
}
cleanup job 0
job 0 -> 10
cleanup job 5
job 5 failed: recovered (runtime error: true): runtime error: index out of range [5] with length 2
cleanup job 1
job 1 -> 20
- Verdict: native.
panicstops the function and runs its deferred calls, then those of each caller. A run-time error such as an index out of range is a panic with a value of typeruntime.Error. recoverstops the panic only when a deferred function calls it directly. The deferred function can then set the named resulterr, so the panic becomes an ordinary error value at the boundary.- Deferred calls run in reverse order. The recovering function was deferred last, so it runs first, and the line
cleanup job 5comes after the recovery.
A panic that no function recovers ends the whole program, even when it starts in another goroutine. recover in main does not help, because it works only in the goroutine that panicked. The program prints the panic value and a stack trace to standard error, and it exits with status 2.
This code fails on purpose. The output below is the error.
package main
import (
"fmt"
"sync"
)
func main() {
defer func() {
fmt.Println("recovered in main:", recover())
}()
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
var items []int
fmt.Println(items[3])
}()
wg.Wait()
}
recover returns nil when it is not called directly by a deferred function. Here the deferred function calls a helper, and the helper calls recover, so the panic goes on.
This code panics, on purpose.
package main
import "fmt"
func logPanic() {
if r := recover(); r != nil {
fmt.Println("recovered:", r)
}
}
func main() {
defer func() {
logPanic()
}()
panic("broken invariant")
}
The fix is defer logPanic(), which makes logPanic itself the deferred function.
use std::panic;
use std::thread;
struct Cleanup(usize);
impl Drop for Cleanup {
fn drop(&mut self) {
println!("cleanup job {}", self.0);
}
}
fn run_job(job: usize, items: &[u32]) -> u32 {
let _guard = Cleanup(job);
items[job] * 10
}
fn main() {
panic::set_hook(Box::new(|_| {}));
let items = [1, 2];
for job in [0, 5, 1] {
match panic::catch_unwind(|| run_job(job, &items)) {
Ok(result) => println!("job {job} -> {result}"),
Err(payload) => {
let message = payload.downcast_ref::<String>().map_or("?", |s| s.as_str());
println!("job {job} failed: {message}");
}
}
}
let worker = thread::spawn(|| -> u32 { panic!("worker found a broken invariant") });
println!("worker joined with an error: {}", worker.join().is_err());
}
cleanup job 0
job 0 -> 10
cleanup job 5
job 5 failed: index out of bounds: the len is 2 but the index is 5
cleanup job 1
job 1 -> 20
worker joined with an error: true
- Verdict: native.
panic!and run-time checks such as an index out of bounds start a panic. By default the panic unwinds the stack and runs thedropof each value, socleanup job 5prints before the failure is reported. catch_unwindstops an unwinding panic and returns it as anErr. Its documentation says that it is not for a general try and catch, and thatResultfits functions that fail on a regular basis. A thread is a second boundary:joinreturnsErrwhen the thread panicked.- The panic hook runs before unwinding. The default hook prints the message and the location to standard error. This program sets an empty hook to keep the output short.
- With
panic = 'abort'in a Cargo profile, a panic ends the process at once. Nodropruns, andcatch_unwindcannot stop it.
A panic that reaches the end of main ends the program with exit status 101.
This code fails on purpose. The output below is the error.
fn main() {
let ports: Vec<u16> = Vec::new();
println!("first port: {}", ports[0]);
}
std::process::abort ends the process at once. It runs no destructors, so the drop of Cleanup does not run.
This code fails on purpose. The output below is the error.
struct Cleanup;
impl Drop for Cleanup {
fn drop(&mut self) {
println!("cleanup");
}
}
fn main() {
let _guard = Cleanup;
std::process::abort();
}
Variations and related ideas
- Assertions. An assertion is the most common way to start a panic on purpose. C
assert, Rustassert!and Javaassertall stop the current work when a condition is false (Assertion). - Fail-fast and let it crash. Gray's fail-fast modules check their inputs, intermediate results, outputs and data structures, and stop when a check fails.1 Armstrong goes further: in the event of an error that the programmer does not know how to handle, "the program should just crash", and another process does the recovery.12
- Panics as error values. At a boundary, a panic often becomes an error value. The Go example sets the named result
errin the deferred function that recovers. The Rust 1.9 announcement gives this as a reason forcatch_unwind: a library can translate a panic into an error on the C side of an interface.6 - Workers and supervisors. A process that stops on a bug needs another process to act on the failure. In Erlang, a worker process does the job, and a supervisor process observes it and corrects the error when the worker fails.12 A restart begins from a clean state, which a recovery in place cannot promise.
- Panics in tests. A test fails when the test function panics. The Rust test runner runs each test in a new thread and marks the test as failed when that thread dies.27 This is a boundary per test (Unit testing).
Pitfalls
Recovery that keeps broken state
A recovery is safe only if it throws away all the state that the failed work touched. Here a transfer takes money from one account, then panics before it adds the money to the other. The handler recovers, logs, and the program goes on. The total is now wrong.
This code runs but gives a wrong answer on purpose.
package main
import "fmt"
var balance = map[string]int{"alice": 100, "bob": 50}
func fee(amount int, rates []int) int {
return amount * rates[len(rates)] / 100
}
func transfer(from, to string, amount int) {
defer func() {
if r := recover(); r != nil {
fmt.Println("recovered:", r)
}
}()
balance[from] -= amount
balance[to] += amount - fee(amount, []int{1, 2})
}
func main() {
fmt.Println("total before:", balance["alice"]+balance["bob"])
transfer("alice", "bob", 30)
fmt.Println("total after:", balance["alice"]+balance["bob"])
}
total before: 150
recovered: runtime error: index out of range [2] with length 2
total after: 120
The fix is to stop the process, or to recover only at a boundary that owns all the state of the work, such as a request with its own data or a transaction that rolls back.
recover in the wrong place
Go recover returns nil when it is not called directly by a deferred function.3 A deferred function that calls a helper, which then calls recover, does not stop the panic (see the indirect block of the Go example). A panic in another goroutine is also out of reach: it ends the whole program, even when main has a deferred recover (see the goroutine block).
Catching too much
A handler for every kind of failure also catches the bugs and the requests to stop. In Python, a bare except: catches SystemExit, so a call of sys.exit does not end the program (see the bare-except block of the Python example). In Java, a handler for Throwable also catches AssertionError and OutOfMemoryError.15 Catch the narrowest type that the code can handle.
Hard stops lose output
os._exit does not flush the standard I/O buffers,24 and C abort may not flush the open streams.9 Text that a program wrote to a buffer just before a hard stop can vanish. A program that must report a failure before it stops writes the report to an unbuffered stream such as standard error, as the C example does.
Code that needs unwinding under abort
catch_unwind does not catch a panic that aborts the process.11 A Rust library that relies on catch_unwind loses its boundary when the application builds with panic = 'abort'. Unwinding across a language boundary, for example from Rust into C, is undefined behaviour.6 Catch the panic before it reaches the foreign code.
A nil panic value in Go
Under the old rule of Go, panic(nil) started a panic for which recover returned nil. A handler that tested recover() != nil could not see it. The rule changed in 2023 (see History). A panic with a nil value now causes a run-time panic of type *runtime.PanicNilError, and recover in a panicking goroutine never returns nil.28
Cost
- Checks on the normal path. Each inserted check, such as a bounds check, is a comparison and a branch on every access. The panic path itself is rarely used.
- Unwinding. The unwinder needs data about each frame, and the cleanup code takes space. The Rust book suggests
panic = 'abort'when the binary must be as small as possible.5 - Abort. An abort costs nothing at the time of the failure, but no cleanup runs. Temporary files stay, buffered output can be lost, and a lock held in a file or a database stays until something else releases it.
- Restart. When the process ends, the service is down until something starts it again. Gray's report describes outages where the restart of a large system took from minutes to an hour.1
History
- 1985. Jim Gray's Tandem report "Why Do Computers Stop and What Can Be Done About It?" described fail-fast software modules and processes that share no state.1
- 2003. Joe Armstrong's thesis described the error handling of Erlang with the slogans "If you can't do what you want to do, die" and "Let it crash".12
- 2016. Rust 1.9 stabilized the module
std::panicwithcatch_unwind, to make isolation boundaries inside a thread.6 - 2023. Go 1.21, released on 8 August 2023, made
panic(nil)a run-time panic of type*runtime.PanicNilError.2829
References
- Jim Gray, Why Do Computers Stop and What Can Be Done About It?, Tandem Technical Report 85.7, June 1985, page 1, Introduction (the time line of an outage); page 11, Fault containment through fail-fast software modules
- The Go Programming Language Specification, Run-time panics
- The Go Programming Language Specification, Handling panics
- Rust standard library, function std::panic::set_hook, the description (the hook runs before the panic runtime; the default hook prints to standard error)
- The Rust Programming Language, Unrecoverable Errors with panic!, Unwinding the Stack or Aborting in Response to a Panic
- The Rust Core Team, Announcing Rust 1.9, Rust Blog, 26 May 2016, Controlled unwinding
- Working Draft, Programming Languages, C++ (N4950, the C++23 draft), [except.ctor], paragraphs 1 and 2
- Rust standard library, function std::process::abort, the description (no destructors run)
- ISO/IEC 9899 working draft N3220 (C23), 7.2.2.1 The assert macro; 7.24.4.1 The abort function; 7.24.4.4 The exit function
- Rust standard library, struct std::thread::JoinHandle, method join (Err when the thread panics)
- Rust standard library, function std::panic::catch_unwind, the description and the Notes
- Joe Armstrong, Making reliable distributed systems in the presence of software errors, PhD thesis, Royal Institute of Technology, Stockholm, December 2003, section 4.3, Error handling philosophy (page 104); section 4.3.2, Workers and supervisors (pages 106 and 107); section 4.4, Let it crash (pages 107 and 108)
- The Rust Programming Language, To panic! or Not to panic!, Guidelines for Error Handling
- Go FAQ, Why does Go not have exceptions?
- Java SE 21 API, class java.lang.Error, the class description and the list of direct subclasses
- Java SE 21 API, class java.lang.Exception, the class description
- Python standard library, Built-in Exceptions, exception SystemExit
- Working Draft, Programming Languages, C++ (N4950, the C++23 draft), [sequence.reqmts], paragraphs 118 to 123 (a[n] and a.at(n))
- Working Draft, Programming Languages, C++ (N4950, the C++23 draft), [except.terminate], paragraphs 1 and 2
- Working Draft, Programming Languages, C++ (N4950, the C++23 draft), [terminate.handler], paragraph 3 (the default handler calls abort)
- Java SE 21 API, class java.lang.Runtime, Java Virtual Machine Termination; methods exit and halt
- .NET API reference, Environment.FailFast Method, the summary of each overload and the example ("The try-finally block is not executed")
- Python standard library, sys, sys.exit
- Python standard library, os, os._exit and os.abort
- Node.js documentation, Process, process.exit([code]); process.abort(); Exit codes (code 1)
- TypeScript Handbook, More on Functions, never
- The Rust Programming Language, How to Write Tests, the paragraph after the first test run ("Each test is run in a new thread")
- Go 1.21 Release Notes, Changes to the language (panic with a nil value and runtime.PanicNilError)
- Go Release History, go1.21.0 (released 2023-08-08)
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag W6XZEH Edit this page History Report an error Markdown