Errors
try … else
try is an expression: on an error, else supplies its value.
try (1 + "two") else "fallback" # → "fallback"
n = try (10 / 0) else 0
n # → 0Several statements go in braces:
price = try {
s = " 42 ".trim
raise("not a number") if !(s ~ /^\d+$/)
s.int
} else {
0
}
price # → 42The error dict
else (e) -> … or else (e) { … } binds the error dict.
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"]| Key | What it holds |
|---|---|
message | the error text |
kind | the kind of error (see below) |
file, line, col | where it happened |
stack | where the calls came from: [{fn, file, line, col}, …], nearest first |
data | the data passed to raise (only if there was any) |
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.
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:
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:
raise("out of stock")raise: out of stockHandling by kind
Pass someone else's error on with raise(e) — the location and the stack are kept.
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
try assert(1 == 2) else (e) -> e["message"] # → "assertion failed"
try assert(false, "empty") else (e) -> e["message"] # → "empty"
assert(true) # → nilassert 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.
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.
try { raise("x") } ensure { println("cleanup") }raise: xError kinds
kind | When |
|---|---|
name | no such variable, function, method |
type | a value of the wrong type |
argument | wrong number or kind of arguments |
index | index out of range, length in destructuring |
key | no such key — fetch, dict destructuring |
zero-division | integer division by zero |
regex | a regular expression does not compile |
json | json.parse with bad input |
http, io | network and files |
timeout, canceled | t.timeout, t.cancel on tasks |
raise | raise and assert without their own kind |
limit | time, steps, depth, size — not caught |
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 # → InfinityWhat 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.
try ((1..1e9).array) else "caught"limit: collection too largeWithout exceptions
A missing value is usually easier to step around than to catch:
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"