7. Error handling: Result and ?

  • chapter 7 of 20
  • 1 min read

Dawn has no exceptions. A recoverable error goes through Result[T, E]; ? takes the value out of an Ok/Some and returns early from an Err/None. For the unrecoverable kind there is panic, which does not return and therefore needs no !io.

fn half(x: Int) -> Result[Int, String] =
  if x % 2 == 0 { Ok(x / 2) } else { Err("${x} is odd") }

fn quarter(x: Int) -> Result[Int, String] = {
  let h = half(x)?
  half(h)
}

pub fn main() -> Unit !io =
  match quarter(20) {
    Ok(v) -> println("got ${v}")
    Err(e) -> println("error: ${e}")
  }
got 5

See also: spec.en.md §8