← All examples

Failures

failures.zg
struct Locker {
    owner: str.utf8,
    items: list[str.utf8]
}

fn stash [lent.mut 'l': Locker, 'item': str.utf8] -> bool or fail[full, bad_item: str.utf8] {
    if list.length[lend 'l'.items] at_least 2 { fail full; }
    if 'item' equal_to str.empty { fail bad_item["(empty)"]; }
    list.append[lend.mut 'l'.items, value give 'item'];
    return true;
}

fn parse_digit ['t': str.utf8] -> int32 or fail[not_a_digit] {
    if 't' equal_to "7" { return 7; }
    fail not_a_digit;
}

fn double_digit ['t': str.utf8] -> int32 or fail[not_a_digit] {
    let 'd' := parse_digit[copy 't'] otherwise fail;      # pass it up
    return 'd' times 2;
}

fn save [lent 'l': Locker] -> fail[disk_full] {
    if list.length[lend 'l'.items] > 1 { fail disk_full; }
}

MAIN {
    let 'mine' := Locker[owner = "Tankun", items = list.empty];
    let 'names' := ["rope", str.empty, "helmet", "torch"];
    for 'n' in lend 'names' {
        let 'ok' := stash[lend.mut 'mine', copy 'n'] otherwise {
            full           { std::print.stored["full, stopping", newln]; break; }
            bad_item 'why' { std::print.stored["bad item ", 'why', newln]; continue; }
        };
        std::print.stored["stored ", 'n', newln];
    }
    let 'a' := double_digit["7"] otherwise 0;
    let 'b' := double_digit["x"] otherwise 0;
    std::print.useful['a', " ", 'b', newln];
    save[lend 'mine'] otherwise { disk_full { std::print.stored["could not save", newln]; } };
    let 'c' := parse_digit["x"] otherwise std::exit[3];
    std::print.stored["unreachable", newln];
}
Output
stored rope
bad item (empty)
stored helmet
full, stopping
14 0
could not save

Exits with code 3.