Errors
A function that can fail says so in its signature, after !. The error is a
value of a type you choose, and the caller has to handle it: an unhandled
error is a compile error, not a crash at run time.
struct ParseError { line: i64 message: Str}
fn parse_port(text: &Str, line: i64) -> i64 ! ParseError { let n = text.trim().to_i64().unwrap_or(-1) if n < 1 || n > 65535 { return ParseError { line, message: "not a port: " + text.trim() } } return n}
let good = try parse_port(&" 8080", 1)let fallback = parse_port(&"eighty", 2) catch 80print(f"{good} {fallback}")let _ = parse_port(&"99999", 3) catch |e| { match e { ParseError(p) => print(f"line {p.line}: {p.message}") } 0}8080 80line 3: not a port: 99999The ways to handle an error:
try f()passes it on to the caller, whose signature must list it too.f() catch fallbackuses another value instead.f() catch |e| { ... }runs a block, which can look at the error.f() catch { ErrorType(e) => ... }matches on the error type directly.
A function can fail in more than one way, -> Str ! IoError | ParseError,
and an error declaration names such a set: error LoadError = IoError | ParseError.
defer runs a statement when the block ends, however it ends, so cleanup
sits next to the setup it belongs to. errdefer runs only when the block
ends with an error.
fn step(name: &Str) { print("start " + *name) defer print("end " + *name) print("in the middle")}step(&"one")start onein the middleend oneAt the top level of a script and in tests, an error that reaches try
stops the program with a message, which keeps small scripts short.