Activity 11 - Error Handling by Hand
Name:
1. Convert panic to Result
#![allow(unused)] fn main() { // Given this function that panics: fn safe_divide(a: i32, b: i32) -> i32 { if b == 0 { panic!("Cannot divide by zero!"); } a / b } // Rewrite it to return a Result instead of panicking: fn safe_divide_result(a: i32, b: i32) -> ______________ { // Your code here } }
2. Error Propagation with match
- Use this helper function to complete
parse_and_double - The helper function handles parsing and returns clear error messages
#![allow(unused)] fn main() { // 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
#![allow(unused)] fn main() { fn parse_and_double_short(input: &str) -> Result<i32, String> { // Your code here (should be 2-3 lines) } }