Skip to content

Panics

Stop the program on purpose with panic, unwrap and expect, and read what a stop says when a check fails.

A panic ends the program. It is for the program that has found itself somewhere it should never be: an index the code has proved in range, a state the types cannot rule out, a value that was promised. It is not for anything a caller can act on; that is a Result, which a caller can match, convert or propagate. A panic gives the caller nothing to match: it is a trap, catch, ? and ?? never see it, and nothing after the call runs, pending defers included.

Every panic says what failed and where. Atoll’s own checks, xs[i] past the end and a division by zero among them, stop the program the same way and say what failed and where.

panic

panic(message) stops the program with message. It has the type !, the type of an expression that does not complete, so it can stand wherever a value is expected without a value to give:

fn lookup(ports Map[string, int], name string) int {
    return ports.get(name) ?? panic("no port named ${name}")
}

fn main() void {
    mut ports: Map[string, int] = Map.new()
    ports.put("http", 80)
    println("${lookup(ports, "http")}")
}

?? takes the map’s value when there is one, and the right-hand side is not evaluated: the message is built only on the way to the stop, and the lookup that succeeds costs what it did without it. A function that ends in a panic needs no return after it, and a match arm that panics joins with the arms that give a value, as return and error do (see Never).

panic, todo, unimplemented and unreachable are the only names this page adds to the language’s bare names:

Call The program stops with
panic("message") message
todo(), todo("why") not yet implemented, and : why after it
unimplemented(), unimplemented("why") not implemented, and : why after it
unreachable(), unreachable("why") internal error: entered unreachable code, and : why after it

todo marks code that is yet to be written, unimplemented code that is not meant to be, and unreachable a place the author knows is never reached:

fn describe(n int) string {
    if n < 0 {
        return "negative"
    }
    if n == 0 {
        return "zero"
    }
    if n > 0 {
        return "positive"
    }
    unreachable("an int is below, at or above zero")
}

fn later(n int) string {
    todo("describe the rest")
}

unwrap and expect

Option and Result have two methods that stop the program when the value is not there. Everything else on them is total. They are for the value the program has already checked, or that the program is wrong to lack; where it is not, a ??, a match or a ? says what to do instead.

Call On None or Err the program stops with
option.unwrap() called `Option.unwrap()` on a `None` value
option.expect(message) message
result.unwrap() called `Result.unwrap()` on an `Err` value: and the error
result.expect(message) message, : and the error

The error is written as its Display form, so a Result can be unwrapped when its error type can be shown, which an error declaration can. It is written into the message and nowhere before it: a Result that holds its value costs the match and nothing else.

error LoadError { Missing { key: string } }

fn load(key string) int ! LoadError {
    if key.is_empty() { error Missing { key: key } }
    return key.len()
}

fn first(xs []int) int {
    return xs.get(0).expect("the list is never empty here")
}

fn main() void {
    println("${first([4, 5]) + load("port").unwrap()}")
}

Each reports the place of the call to unwrap or expect, not a line of the standard library.

What a check says

The checks the compiler writes into a program stop it the same way. Each says what failed, and the stack says where:

The check The program stops with
xs[i], xs.set(i, v), xs.update(i, f) index out of range
s[i] on a string string index out of range
xs[a..b], xs[a..=b], s[a..b], s[a..=b], and the open forms xs[a..], xs[..b], xs[..=b] slice out of range
m[key] for a key the map lacks key not found: the map has no entry for the key
n / 0, n % 0 division by zero
a signed minimum / -1 or % -1 division overflow: the least value of a signed type divided by -1 does not fit
xs.chunked(0) chunk size must be positive: the size is 0
xs.windowed(size, step) with either not positive window size and step must be positive: the size is 2 and the step is 0
random.below(0) random bound must be positive: no value is below zero

The index and the length are not in index out of range, nor the range in slice out of range, and that is a cost decision, not an oversight. A check can leave the numbers it looked at only in stores on its failing edge, and the engine lays a function out differently around an edge that holds stores than around one that is only the trap: registers are moved about in code that never fails, and a loop that never fails a check runs whole percents slower for the numbers it would have said. So the checks that sit in the loops of ordinary programs say what failed and where, from a table the module carries and the code does not feel, and leave the numbers out; the program that cannot find the bad index prints it, or tests it with get. The checks that sit in no loop, the sizes of chunked and windowed, say theirs.

The checks the program does not write say what failed too. An allocation the allocator refuses stops with out of memory: the allocator refused a block; intrinsics.trap() says that the program stopped itself; and the standard library’s own invariants, such as a string builder that cannot make the room it asked for, each have a sentence of their own. A stop that no check of the program explains, which is a bug in atoll, says internal error and asks for a report.

Running out of stack is not one of these checks. It is a resource limit, as in Rust, and not an event a program can count on: the optimizer may turn a recursion into a loop, so a recursion with no end that stops at -O0 may run forever at -O2. A program that needs a bound on its depth counts the depth itself.

What a stop looks like

atoll run says the stop on standard error, then the calls that led to it, innermost first, each with its file, line and column. Under the first, the line of source is shown with the expression underlined:

fn lookup(ports &Map[string, int], name &string) int {
    return ports.get(name) ?? panic("no port named ${name}")
}

fn work(ports &Map[string, int], name string) int {
    defer println("closed")
    return lookup(ports, name) + 1
}

fn main() void {
    mut ports: Map[string, int] = Map.new()
    ports.put("http", 80)
    println("${work(ports, "http")}")
    println("${work(ports, "ftp")}")
}
$ atoll run main.at
closed
81
atoll run: trap: no port named ftp
  at lookup (main.at:2:31)
  2 |     return ports.get(name) ?? panic("no port named ${name}")
    |                               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  at work (main.at:7:12)
  at main (main.at:14:16)

The first call to work closed, as it returned; the second did not, since a panic runs nothing on the way out. The exit status is nonzero.

The stack names functions as the program does. A method is Account.withdraw, a generic is what it was made for, List[int].get or get_it[int], and a closure is named by the function that holds it, main.{closure}. A call the compiler inlined is still a frame, so an @inline function does not vanish from a stack. Each caller’s frame is at the call, the line and column of lookup(ports, name), and not of the return around it.

The standard library’s own frames are left out of a stack, since a reader did not write them and the call that matters is the one in the program. To see them, set ATOLL_BACKTRACE=full. This program stops in List.set, and the stack names the call in reset that led there:

fn reset(xs []int, i usize) []int {
    mut ys := xs
    ys.set(i, 0)
    return ys
}

fn main() void {
    n := reset([1, 2, 3], 5usize).len()
    println("${n}")
}
$ atoll run main.at
atoll run: trap: index out of range
  at reset (main.at:3:5)
  3 |     ys.set(i, 0)
    |     ^^^^^^^^^^^^
  at main (main.at:8:5)

$ ATOLL_BACKTRACE=full atoll run main.at
atoll run: trap: index out of range
  at List[int].set (std/list.at:3861:27)
  at reset (main.at:3:5)
  at main (main.at:8:5)

A stack made of the standard library’s frames alone is shown whole.

Telling a helper’s caller

A helper that checks something for its callers should be reported at the call, not at its own panic. A parameter marked @call_site is filled by the compiler with a record of where each call is (see Writing your own); passing it to panic as the last argument reports the stop there, and the helper is not in the stack:

import site

fn must_be_even(n int, @call_site at &site.CallSite) void {
    if n % 2 != 0 {
        panic("${n} is odd", at)
    }
}

fn halve(n int) int {
    must_be_even(n)
    return n / 2
}

fn main() void {
    println("${halve(8)}")
}

halve(3) stops at the call of must_be_even in halve, with 3 is odd. unwrap, expect and the other panics in the standard library are written the same way, which is why their stops are at the call a reader wrote.

In a test

atoll test fails a test that stops, and keeps going with the next. The result carries the sentence and the calls under the test’s name:

    FAIL [   0.002s] calc.at: reads past the end
        index out of range
          at pick (calc.at:2:12)
          2 |     return xs[i]
            |            ^^^^^
          at test "reads past the end" (calc.at:10:5)

atoll test --format json carries it as data, in a trap object on the test: the message, the kind (index_out_of_range, slice_out_of_range, key_missing, divide_by_zero, panic, and so on), the file, line, column and function of the first frame of the program’s own, and the frames, each with its function, file, line, column, whether it is library code and whether it is waiting. The MCP server’s test tool answers the same document.

Choosing

Reach for a Result when the caller can do something about the failure, and an Option when absence is data. Reach for a panic when the failure is a mistake in the program: when there is no sensible value to hand back, and a caller who got one would only pass the mistake along. unwrap is the shortest way to say a value is there, and expect the one that says why it must be.

Type to search…

↑↓ navigate↵ selectEsc close