Panics
Also known as: panic crash abort fatal error division by zero index out of range overflow exit code panic in a task unwinding thread panic
● Intermediate4 minBefore this: ErrorsSpec 5.6
A panic stops the program at once, or only its task in a task. It is for bugs, not for failures you expect.
fn share(total: Int, people: Int) -> Int {
total / people
}
fn main() {
print(share(100, 4))
print(share(100, 0))
}The program ran, then stopped with a panic:
kavach run share.kav
25panic: division by zero
A panic happens on:
- an index past the end of a list, and a division by zero;
- a whole number too big for its type (checked in every build);
- a broken contract, and calls nested too deeply;
- running out of memory:
panic: out of memory (asked for N bytes), with no file and line, because nothing more may be asked of memory; - an explicit
panic("…").
Expected failures, such as bad input or a missing file, are errors (!), not panics. A panic means the program itself is wrong.
A panic in a task
A panic in a task stops only that task, as in Tokio and Java. The rest of the program goes on:
fn third(items: [Int]) -> Int {
items[2]
}
fn main() {
const t = spawn third([1, 2])
print("main waits")
match t.wait() {
ok(n) => print("third: {n}")
err(e) => print("{e}")
}
print("main goes on")
}kavach run src/main.kav
main waits panicked: index 2 is out of range: the list has 2 items at src/main.kav:2 main goes on panic: index 2 is out of range: the list has 2 items at src/main.kav:2
- The panic is printed to standard error when it happens, with its place. It is shown after the program's output here, but it came before
panicked: …. .wait()on that task fails with an error whose message ispanicked: <message> at <file>:<line>.- The program ends as usual, with code
0. - A panic in the main task still ends the program, with code
101. - A panic in an agent's handler stops just that handler, and the send fails the same way: see Running an Agent.