Standard Library: Err
Throw and catch recoverable errors
The Err module allows programs to signal and respond to anticipated errors using the throw/try style control flow found in other programming languages.
Err.orElse(func, default)
Call the zero-argument function func. If
func returns a value without throwing an error, return
it; otherwise return default.
fn inverse(n)
if n == 0 then
Err.throw("n must not be zero")
end
1 / n
end
Err.orElse(fn() inverse(5) end, none)
Err.orElse(fn() inverse(0) end, none)
0.2
none
Err.throw(payload)
Throw an error with a payload, which may be any type of
value. Functions which throw errors should be called using
try to avoid unhandled errors.
fn inverse(n)
if n == 0 then
Err.throw("n must not be zero")
end
1 / n
end
inverse(0)
Error: unhandled error
Err.try(func, handler)
Call the zero-argument function func. If
func returns a value without throwing an error, return
it; otherwise, call handler with the error payload and
return handler(payload).
fn inverse(n)
if n == 0 then
Err.throw("n must not be zero")
end
1 / n
end
fn showErr(msg)
"an error occured: $msg"
end
Err.try(fn() inverse(5) end, showErr)
Err.try(fn() inverse(0) end, showErr)
0.2
"an error occured: n must not be zero"