Applied Intermediate
15 Custom errors
Real programs have more than one failure mode. Model them as one error enum, teach it to convert from lower-level errors, and let ? do the plumbing.
Implement safe_div: return Err(MathError::DivByZero) when the divisor is 0, otherwise Ok of the quotient.
Hints
if b == 0 { Err(MathError::DivByZero) } else { Ok(a / b) }.
Reveal solution
#[derive(Debug, PartialEq)]
enum MathError { DivByZero }
fn safe_div(a: i32, b: i32) -> Result<i32, MathError> {
if b == 0 {
Err(MathError::DivByZero)
} else {
Ok(a / b)
}
}