7. Error handling: Result and ?
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")
}
Open in playground
got 5