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.

Step 1 / 2

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) }.
15_error_enum.rs
Reset to starterCompiled in a sandbox; hidden checks must pass.
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)
    }
}