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 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 theFrom<ParseIntError>impl to convert the error.- Guard the zero divisor with an early
return Err(MathError::DivByZero);.
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)
}