Skip to content

Errors ​

try … else ​

try is an expression: on an error, else supplies its value.

mzs
try (1 + "two") else "fallback"  # → "fallback"
n = try (10 / 0) else 0
n  # → 0

Several statements go in braces:

mzs
price = try {
  s = "  42 ".trim
  raise("not a number") if !(s ~ /^\d+$/)
  s.int
} else {
  0
}
price  # → 42

The error dict ​

else (e) -> … or else (e) { … } binds the error dict.

mzs
try (1 + "two") else (e) -> e["kind"]  # → "type"
try (1 + "two") else (e) -> e["message"]  # → "cannot add string to int"
try (1 + "two") else (e) -> e["line"]  # → 3
try (1 + "two") else (e) { e.keys }  # → ["message","kind","file","line","col","stack"]
KeyWhat it holds
messagethe error text
kindthe kind of error (see below)
file, line, colwhere it happened
stackwhere the calls came from: [{fn, file, line, col}, …], nearest first
datathe data passed to raise (only if there was any)
mzs
fn inner() { raise("boom") }
fn outer() { inner() }
try outer() else (e) { e["stack"].map { "${it["fn"]}:${it["line"]}" } }  # → ["inner:2","outer:3"]

raise ​

raise(message) is an error of kind raise. A second argument sets your own kind.

mzs
try raise("out of stock") else (e) -> [e["kind"], e["message"]]  # → ["raise","out of stock"]
try raise("no such order", "user") else (e) -> e["kind"]  # → "user"

A dict with the keys message, kind, data is an error with data:

mzs
fn charge(sum) {
  raise({message: "not enough money", kind: "billing", data: {short_by: 30}})
}
try charge(100) else (e) -> "short by ${e["data"]["short_by"]}"  # → "short by 30"

The kinds syntax, limit, exit, internal are not available to a script.

An unhandled error ends the script:

mzs
raise("out of stock")
text
raise: out of stock

Handling by kind ​

Pass someone else's error on with raise(e) — the location and the stack are kept.

mzs
fn attempt(f) {
  try f() else (e) {
    match e["kind"] {
      "user" -> "refused: ${e["message"]}"
      "zero-division" -> "division by zero"
      else -> raise(e)
    }
  }
}
attempt { raise("bad input", "user") }  # → "refused: bad input"
attempt { 1 / 0 }  # → "division by zero"
try attempt { nil.upper } else (e) -> e["kind"]  # → "name"

assert ​

mzs
try assert(1 == 2) else (e) -> e["message"]  # → "assertion failed"
try assert(false, "empty") else (e) -> e["message"]  # → "empty"
assert(true)  # → nil

assert is an ordinary raise of kind raise; it is never turned off.

ensure ​

ensure { … } runs on any exit from try: success, error, return, break. Its value is discarded.

mzs
log = []
r = try {
  log.push("work")
  1 / 0
} else {
  "error"
} ensure {
  log.push("cleanup")
}
r  # → "error"
log  # → ["work","cleanup"]

Without else the error is not caught: ensure runs, and the error goes on.

mzs
try { raise("x") } ensure { println("cleanup") }
text
raise: x

Error kinds ​

kindWhen
nameno such variable, function, method
typea value of the wrong type
argumentwrong number or kind of arguments
indexindex out of range, length in destructuring
keyno such key — fetch, dict destructuring
zero-divisioninteger division by zero
regexa regular expression does not compile
jsonjson.parse with bad input
http, ionetwork and files
timeout, canceledt.timeout, t.cancel on tasks
raiseraise and assert without their own kind
limittime, steps, depth, size — not caught
mzs
try (7 / 0) else (e) -> e["kind"]  # → "zero-division"
try ({a: 1}.fetch("b")) else (e) -> e["kind"]  # → "key"
try ([1, 2].insert(9, 3)) else (e) -> e["kind"]  # → "index"
7.0 / 0  # → Infinity

What try does not catch ​

Limits (run time, step budget, recursion depth, collection size) and exit(code) end the script past try, and ensure does not run after them. Compile errors are not caught either — the program does not start.

mzs
try ((1..1e9).array) else "caught"
text
limit: collection too large

Without exceptions ​

A missing value is usually easier to step around than to catch:

mzs
cfg = {http: {port: 8080}}
cfg.dig("http", "host") ?? "0.0.0.0"  # → "0.0.0.0"
cfg["proxy"]?.len  # → nil
"abc".int  # → 0
try cfg.fetch("proxy") else "none"  # → "none"