Grav v1.14.0

Panic

import "std/core" (included in import "std") · namespace std.core

Recovering from panics. A panic (from panic(...), a failed assert, a null reference, a stack overflow, running out of memory) normally stops the program. Inside a recovery point, it unwinds to that point instead: finally blocks run on the way, no catch can stop it, and the recovery point gets the message.

Panic.recover(body) is a recovery point. Each HttpServer request and each Thread body is one too.

grav
import "std"

fn risky(n: int) -> int {
    if (n == 0) { panic("n must not be zero") }
    return 100 / n
}

fn main() {
    for (n in [5, 0]) {
        let failure = Panic.recover(fn() { print(risky(n)) })
        if (failure != "") { print("recovered: ${failure}") }
    }
    print("recovery on: ${Panic.recoveryEnabled()}")
}
Output
20
recovered: panic: n must not be zero
recovery on: true

Recovery can be turned off: for every thread with Panic.setRecovery(false), for the current thread with Panic.setThreadRecovery(false), or from the start with the environment variable GRAV_PANIC_RECOVERY=off. A thread's own setting wins over the global one until followGlobalRecovery(). With recovery off, a panic stops the program even inside a recovery point, which is useful while debugging.

See Errors: panics.

API

class Panic

Static members

  • static fn recover(body: fn()) -> string — Run body. Returns "" when it finished; otherwise what stopped it: "panic: <message>" (when recovery is enabled for this thread) or "uncaught exception: <message>".
  • static fn setRecovery(on: bool) — Turn recovery on or off for every thread (threads with their own setting keep it).
  • static fn setThreadRecovery(on: bool) — Turn recovery on or off for the calling thread only.
  • static fn followGlobalRecovery() — Drop the calling thread's own setting: follow the global one again.
  • static fn recoveryEnabled() -> bool — Whether a panic on this thread would be recovered right now.

Edit this page on GitHub