The Error Catch-all
● Intermediate3 minBefore this: trySpec 5.5
! Error accepts any error. Use it in scripts and in main, where you just want to stop with a message.
fn check(age: Int) -> Int ! Error {
if age < 0 {
fail Error("age can't be negative: {age}")
}
age
}
fn main() ! Error {
const a = try check(31)
const b = try check(27)
print("together {a + b}")
}The program ran and printed:
kavach run main-error.kav
together 58If any try in main fails, the program prints error: and the message to standard error, and exits with code 1. Error("…") makes an error that is only a message:
fn check(age: Int) -> Int ! Error {
if age < 0 {
fail Error("age can't be negative: {age}")
}
age
}
fn main() {
print(check(31) catch _ => -1)
const r = check(-2) catch e => {
print("failed: {e}")
0
}
print(r)
}The program ran and printed:
kavach run message.kav
31failed: age can't be negative: -20
A caller can still ask which error an Error holds, with match e { FsError.NotFound(p) => …, _ => … }: see Kinds of Errors. In a library, name your errors (! AgeError), so callers know exactly what can go wrong.