Guides · 08
defer, recover, and panic
Vyi has two ways for things to go wrong, and they never overlap:
- Errors are values. A function that can fail in a way its caller should handle returns an optional or an error union, and the caller deals with it using
tryandcatch. A missing file and bad input are errors. Guide 07 covers them. - A panic is a bug. It means something the program promised would hold didn't, like an index past the end of an array. A panic carries a message for the person reading the crash and unwinds the stack.
This guide covers panics, how to catch one with recover, and defer, the
cleanup mechanism that both kinds of failure share.
defer
defer schedules a statement, or a block, to run when the enclosing function
exits, whichever way it exits:
import { println } from "@fmt"
fn greet() {
defer println("cleanup")
println("body")
}
fn main() !u8 {
greet() // prints body
// prints cleanup
return Ok(0)
}greet prints body first. The deferred println waits until greet
returns.
Defers run on every exit
A normal return, reaching the end of the body, an error leaving through
try, and a panic unwinding through the function all run its defers. Cleanup
written with defer can't be skipped by an exit path you forgot about:
import { println } from "@fmt"
enum ConfigError { Invalid }
fn parsePort(raw: i32) ConfigError!i32 {
if raw <= 0 { return Err(Invalid) }
return Ok(raw)
}
fn loadPort(raw: i32) ConfigError!i32 {
defer println("closing")
con port = try parsePort(raw)
return Ok(port)
}
fn main() !u8 {
con good = loadPort(8080) catch 0 // prints closing
con bad = loadPort(-1) catch 0 // prints closing
println(good) // prints 8080
println(bad) // prints 0
return Ok(0)
}The first call returns normally. In the second, try passes the Err from
parsePort up to the caller, which leaves loadPort early. The defer runs
both times.
Defers run in reverse order
When a function has several defers, the last one registered runs first. So teardown mirrors setup:
import { println } from "@fmt"
fn session() {
println("open socket")
defer println("close socket")
println("begin session")
defer println("end session")
}
fn main() !u8 {
session() // prints open socket
// prints begin session
// prints end session
// prints close socket
return Ok(0)
}A defer belongs to the function, not the block
A defer runs when the function exits, not when the block it's written in
ends. If you know defer from a language where it runs at the end of the
block, this is the difference to remember. A defer inside an if waits for
the whole function:
import { println } from "@fmt"
fn save(compress: bool) {
if compress {
defer println("compressor closed")
println("compressing")
}
println("writing file")
}
fn main() !u8 {
save(true) // prints compressing
// prints writing file
// prints compressor closed
return Ok(0)
}A defer is registered when execution reaches it. A defer that execution
never reaches never runs: save(false) prints only writing file. A defer
inside a loop body registers once for each pass through the loop, and all of
them run when the function exits.
A defer sees final values
The body of a defer is ordinary code that can use the function's local
bindings. It runs at exit, so it sees their values at exit, not their values
when the defer was registered:
import { println } from "@fmt"
fn download() i32 {
mut received = 0
defer println($"received ${received} bytes")
received = 512
return received
}
fn main() !u8 {
con n = download() // prints received 512 bytes
println(n) // prints 512
return Ok(0)
}A return inside a defer sets the result
A return inside a defer body replaces the value the function returns:
import { println } from "@fmt"
fn score() i32 {
defer { return 100 }
return 1
}
fn main() !u8 {
println(score()) // prints 100
return Ok(0)
}On its own this is rarely what you want. Its real job is in recover, below.
panic
panic reason stops what the function is doing and starts unwinding the
stack. The reason is a [*con]u8, and a string literal is one:
import { println } from "@fmt"
fn half(n: i32) i32 {
if n % 2 != 0 { panic "odd input" }
return n / 2
}
fn main() !u8 {
println(half(10)) // prints 5
return Ok(0)
}A panic has no error type for a caller to inspect. It's for a person reading
a crash. Anything a caller should handle belongs in an error union instead.
The reason must be a [*con]u8, so a $"…" template doesn't work as one:
import { println } from "@fmt"
fn failAt(step: i32) {
panic $"step ${step}" // error: a `panic` reason is a `[*con]u8`
}
fn main() !u8 {
println("starting")
failAt(3)
return Ok(0)
}An uncaught panic ends the program
A panic unwinds one function at a time and runs each function's defers on the
way out. If nothing catches it, it leaves main. Then the program prints
panic:, the reason, and the calls that led to the panic, all on stderr, and
exits with status 101:
import { println } from "@fmt"
fn half(n: i32) i32 {
if n % 2 != 0 { panic "odd input" }
return n / 2
}
fn main() !u8 {
defer println("main exits")
println(half(7))
return Ok(0)
}main exits
panic: odd input
at main.vyi:10:13main exits goes to stdout: the defer in main runs before the program
stops. Each at line is a call that was in progress, as file, line, and
column, with the innermost call first. Here there is one: the call to half
on line 10.
The list shows at most the 32 innermost calls. Each call that can end in a panic writes its location to a fixed-size table, which holds 4,096 calls on wasm and 2,730 on x86-64 and arm64. Deeper recursion still runs normally, but calls past the table's end aren't written down. When a panic happens down there, the list ends with a line counting the calls it couldn't show. A recursive function that panics 5,000 calls deep on wasm prints:
panic: bottom
at main.vyi:3:12
at main.vyi:3:12
…
… 905 deeper frames not recordedThe runtime panics too
Some operations panic when their rules are broken. The first one you'll meet
is indexing past the end: indexing a [*con]T is bounds-checked.
import { println } from "@fmt"
fn main() !u8 {
con word = "abc"
println(word[7])
return Ok(0)
}This program compiles. Run it and it stops:
panic: array index out of boundsInteger arithmetic panics the same way. Division or remainder by zero panics
with division by zero in every build mode. In a debug build, an integer +,
-, *, or negation whose result doesn't fit its type panics with
integer overflow. A release build wraps instead (guide
02 and the
operators reference).
Standard-library functions check their inputs the same way. copy from
@mem, for example, panics when the destination is smaller than the source.
recover
recover catches a panic. It can only appear inside a defer body, because
the only time a panic can be stopped is while the unwind is running a
function's defers:
import { println } from "@fmt"
fn explode() i32 {
panic "kaboom"
}
fn safe() i32 {
defer {
recover(reason) {
println($"recovered: ${reason}")
return 7
}
}
return explode()
}
fn main() !u8 {
con v = safe() // prints recovered: kaboom
println(v) // prints 7
return Ok(0)
}How it works:
recover(reason) { … }binds the panic's reason asreason, a[*con]u8, and runs the block. It does so only when the defer is running because of a panic. When the function returns normally or with an error, the rest of the defer body runs and therecoverblock is skipped.- A
returninside the block sets the function's return value and stops the unwind. The caller sees an ordinary return. - A
recoverblock without areturnonly looks at the panic. The unwind goes on to the defers of the calling function, and ends the program if nothing stops it. Use this to log a crash without hiding it. - When you don't need the reason, write
recover(_).
Outside a defer, recover is an error:
fn main() !u8 {
recover(_) { // error: usable only inside a `defer`
return Ok(1)
}
return Ok(0)
}recover catches panics only. An error leaving through try is a value, not
an unwind: it runs your defers but never your recover blocks. To handle an
error, catch it.
Cleanup and recovery together
The usual shape is: set something up, defer the cleanup, and, where a crash
in the work shouldn't take down the whole program, put a recover in the same
defer, after the cleanup.
import { println } from "@fmt"
mut activeJobs = 0
fn half(n: i32) i32 {
if n % 2 != 0 { panic "odd input" }
return n / 2
}
fn runJob(n: i32) i32 {
activeJobs += 1
defer {
activeJobs -= 1
recover(reason) {
println($"failed: ${reason}")
return -1
}
}
return half(n)
}
fn main() !u8 {
println(runJob(10)) // prints 5
println(runJob(7)) // prints failed: odd input
// prints -1
println(activeJobs) // prints 0
return Ok(0)
}For runJob(10), the defer lowers the job count and skips the recover
block. For runJob(7), half panics, the unwind reaches the defer, the job
count still goes down, and the recover block makes runJob return -1
normally.
A recover can sit any number of calls above the panic. The unwind runs the
defers of every function between the panic and the recover, so nothing in
between misses its cleanup:
import { println } from "@fmt"
mut unwound = 0
fn descend(depth: i32) i32 {
defer { unwound += 1 }
if depth == 0 { panic "bottom" }
return descend(depth - 1)
}
fn guarded() i32 {
defer { recover(_) { return 0 } }
return descend(3)
}
fn main() !u8 {
con v = guarded()
println(v) // prints 0
println(unwound) // prints 4
return Ok(0)
}descend(3) calls itself down to descend(0), which panics. All four calls
run their defer on the way out before guarded recovers.
Reading the call stack with @trace
The call locations that a crash prints are also available to your program,
through the @trace package. currentPos(skip) returns the line and column
of a call in progress: currentPos(0) is the call to currentPos itself,
currentPos(1) is the call to the function that called it, and so on. A
checking helper can use this to report where it was called from:
import { println } from "@fmt"
import { currentPos } from "@trace"
fn check(ok: bool) {
if ok { return }
con at = currentPos(1)
println($"check failed at line ${at.line}")
}
fn main() !u8 {
check(2 + 2 == 4)
check(2 + 2 == 5) // prints check failed at line 12
return Ok(0)
}currentFile(skip) returns the file of the same call, and trace(skip)
returns all the calls in progress as a [*con]Frame, outermost first, where
each Frame has a file, a line, and a col. All three read the same
table as the crash printout. For a call that isn't in the table, currentPos
returns line and column 0 and currentFile returns "", and in recursion
deeper than the table holds, trace stops at the deepest call it recorded.
Stack overflow
Every call uses some stack, and the stack is finite. A recursion that never stops, or goes too deep, ends the program when the stack runs out:
fn countDown(n: i32) i32 {
return countDown(n - 1) + 1 // never stops
}
fn main() !u8 {
return Ok(u8(countDown(10)))
}vyi run: stack overflowRunning out of stack isn't a panic. Nothing unwinds, no defer runs, recover
never sees it, and the program exits with a non-zero status:
- On wasm, the stack is 1 MiB. A function that keeps values on the stack checks the limit each time it's called, and
vyi runprintsvyi run: stack overflowand exits with status 1. - On x86-64 and arm64, the program uses the operating system's stack, commonly 8 MiB, with a guard page below it that stops the program with a segmentation fault.
vyi runreports the signal and exits with status 139. A function whose stack frame is larger than a page, such as one with a big local array, touches the frame one 4 KiB page at a time as it reserves it, so it reaches the guard page before it can step past it.
Either way, the program stops before it writes past the end of its stack.
Choosing the wasm stack size in package.vyipac or with a build flag is
(planned).
The compiler doesn't reject recursion that never ends. Stopping it is up to your program.
See also the statements reference.