5. Optionals and traps

?T is a value or nil, and the compiler forces the check before use. Failures are TRAPS: named, catchable, never silent. try ... catch (e) is an expression; e carries code, line, method and message. Anything uncaught ends the program with the same structured report.

let n = parse_int("42x");   -- ?Int
if n == nil {
  print("not a number");
}

let r = try fs.read_all("/etc/missing", 4096) catch (e) e.msg;
print(r);   -- the file's bytes, or "No such file or directory"

let d = 0;
let q = try 10 / d catch (e) 0 - 1;   -- DIV0 is a trap, caught here

Chapters