Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Activity 13: Error Handling by Hand

Name:



1. The empty list problem

On Monday we wrote average for the grade tracker, and gave it a bad answer for a student with no grades yet:

fn average(&self) -> f64 {
    if self.grades.len() == 0 {
        return 0.0;          // an average of zero? they have no grades
    }
    let mut total = 0.0;
    for grade in &self.grades {
        total += grade;
    }
    total / self.grades.len() as f64
}

A student with no grades and a student failing everything both come back as 0.0. Nothing that calls this can tell them apart.

(a) Fill in a return type that can say "there is no average yet", and rewrite the body to match.

fn average(&self) -> ______________ {






}







(b) You had a choice here for your return type. What did you pick and why?




2. Error Propagation with match

  • Use this helper function to complete parse_and_double
  • The helper function handles parsing and returns clear error messages
// Helper function (already written for you):
fn parse_int(input: &str) -> Result<i32, String> {
    match input.parse::<i32>() {
        Ok(num) => Ok(num),
        Err(_) => Err(format!("'{}' is not a valid number", input)),
    }
}

// Complete this function using the helper:
fn parse_and_double(input: &str) -> Result<i32, String> {
    let num = match parse_int(input) {

        ___________ => ___________,

        ___________ => ___________,
    };

    let doubled = ___________;

    _____________
}

3. Using the ? operator

  • Rewrite the parse_and_double function using the ? operator
  • Use the same helper function from problem 2
fn parse_and_double_short(input: &str) -> Result<i32, String> {
    // Your code here (should be 2-3 lines)








}

Solutions

Problem 1: The empty list problem

fn average(&self) -> Option<f64> {
    if self.grades.len() == 0 {
        return None;
    }
    let mut total = 0.0;
    for grade in &self.grades {
        total += grade;
    }
    Some(total / self.grades.len() as f64)
}

Part (b) Option is the better fit but Result is defensible:

  • Option says there is no average. A student with no grades yet is not an error, it is a normal state at the start of term. There is nothing to report to anyone
  • Result<f64, String> works and will compile, but it forces you to invent an error message for something that has not gone wrong

Problem 2: Error Propagation with match

Several alternatives to parse_and_double:

fn parse_and_double(input: &str) -> Result<i32, String> {
    let num = match parse_int(input) {
        Ok(n) => n,
        Err(e) => return Err(e),
    };
    let doubled = num * 2;
    Ok(doubled)
}

Or having both arms of the match "do" something:

fn parse_and_double(input: &str) -> Result<i32, String> {
    let mut num = 0; // can also just say `let mut num` but we haven't covered that
    match parse_int(input) {
        Ok(n) => num = n,
        Err(e) => return Err(e),
    };
    let doubled = num * 2;
    Ok(doubled)
}

Or letting the whole match just be an expression so that's what gets returned:

fn parse_and_double(input: &str) -> Result<i32, String> {
    match parse_int(input) {
        Ok(n) => Ok(n*2),
        Err(e) => Err(e),
    }
}

Problem 3: Using the ? operator

Which leads us to the most concise versions with ?:

fn parse_and_double(input: &str) -> Result<i32, String> {
    let num = parse_int(input)?;
    Ok(num * 2)
}

Or even shorter:

fn parse_and_double(input: &str) -> Result<i32, String> {
    Ok(2*parse_int(input)?)
}