Skip to content
Kavachकवच

Matching Errors

● Intermediate4 minBefore this: Errors, MatchSpec 5.4

match on a call that can fail: ok(value) for success, err(…) for each kind of error.

type AgeError = Empty | NotANumber(text: String) | TooLarge(value: Int)

fn parse_age(text: String) -> Int ! AgeError {
    if text.is_empty() {
        fail AgeError.Empty
    }
    const n = Int(text) catch _ => fail AgeError.NotANumber(text: text)
    if n > 150 {
        fail AgeError.TooLarge(value: n)
    }
    n
}

fn report(input: String) {
    match parse_age(input) {
        ok(age) => print("Age is {age}")
        err(AgeError.Empty) => print("Please enter an age")
        err(AgeError.NotANumber(text)) => print("'{text}' is not a number")
        err(AgeError.TooLarge(value)) => print("{value} is too large")
    }
}

fn main() {
    report("31")
    report("")
    report("abc")
    report("999")
}

The program ran and printed:

kavach run match.kav

Age is 31Please enter an age'abc' is not a number999 is too large
match.kav: Kavach code, then what running it prints

Each error variant gets its own message, with its details taken apart. As with every match, leaving a case out is a compile error, so a new kind of error can't slip through unhandled.