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 2 / 2

Implement parse_div: parse both strings, then divide. A parse failure becomes MathError::Parse automatically via the From impl, so you can use ?.

Hints
  • let x: i32 = a.parse()?; -- ? uses the From<ParseIntError> impl to convert the error.
  • Guard the zero divisor with an early return Err(MathError::DivByZero);.
15_error_enum.rs
Reset to starterCompiled in a sandbox; hidden checks must pass.
Reveal solution
#[derive(Debug, PartialEq)]
enum MathError { Parse, DivByZero }

impl From<std::num::ParseIntError> for MathError {
    fn from(_: std::num::ParseIntError) -> Self { MathError::Parse }
}

fn parse_div(a: &str, b: &str) -> Result<i32, MathError> {
    let x: i32 = a.parse()?;
    let y: i32 = b.parse()?;
    if y == 0 {
        return Err(MathError::DivByZero);
    }
    Ok(x / y)
}