Errors and contracts

Errors are values

Cresset has no hidden exceptions. A function that can fail returns a result: either ok(value) or err(message). The failure is part of what the function gives back, so you can see it in the code.

fn parse_age(text) -> result[num]:
    n = to_int(text)?
    if n < 0: return err("age can't be negative")
    return ok(n)

fn main() needs print:
    print(parse_age("42"))
    print(parse_age("x"))
    print(parse_age("-3"))

This prints ok(42), then err("'x' is not a whole number"), then err("age can't be negative").

The ? operator

Putting ? after a result means: if it worked, give me the value; if it failed, return that failure from this function right away. It is what keeps result code short.

fn first_line_length(path) needs read:
    text = read(path)?
    first = text.lines().first()
    return ok(first.len())

fn main() needs print, read:
    print(first_line_length("examples/scores.txt"))

read returns a result, so ? either unwraps the text or passes the failure up. A function that uses ? should return a result too.

Working with results

MethodMeaning
is_ok() / is_err()Did it work?
unwrap()The value, or stop with an error if it failed
unwrap_or(default)The value, or a default if it failed
error()The failure message (stops if it was ok)
map(f)Change the value inside an ok

list.try_map(f) applies a function that returns results to every item and stops at the first failure, giving back one result for the whole list. For example, lines.try_map(to_int) turns lines of text into numbers or the first problem.

Contracts

A contract states what a function expects and promises, right in its signature.

fn withdraw(balance, amount) requires amount > 0 and amount <= balance ensures result >= 0:
    return balance - amount

fn main() needs print:
    print(withdraw(100, 30))

When a promise breaks, the program stops and names exactly which one:

error: contract broken: 'withdraw' requires amount > 0 and amount <= balance
  help: it was called with (100, 500)

Contracts are checked while the program runs, not before.

Error messages

Cresset's errors show the file and line, the code, and a suggestion. A misspelled name gets a "did you mean":

error: I don't know the name 'totl'
  --> program.crs:3
   |  print(totl)
help: did you mean 'total'?

Next

Reproduce any run exactly: Record and replay.