Complete the code to return a Result type from the function.
fn divide(a: f64, b: f64) -> [1] { if b == 0.0 { Err("Cannot divide by zero") } else { Ok(a / b) } }
Option instead of Result when you want to provide error details.f64 without error handling.The function returns a Result type to handle success (Ok) and error (Err) cases properly.
Complete the code to propagate errors using the ? operator.
fn read_number_from_file() -> Result<i32, std::io::Error> {
let content = std::fs::read_to_string("number.txt")[1];
let num: i32 = content.trim().parse().unwrap();
Ok(num)
}.unwrap() which panics on error instead of propagating it..ok() which converts to Option and loses error info.The ? operator propagates errors automatically, making error handling concise.
Fix the error in the match expression to handle both Ok and Err variants.
match result [1]{ Ok(value) => println!("Value: {}", value), Err(e) => println!("Error: {}", e), }
The match expression requires braces {} to enclose its arms.
Fill in the blank to create a custom error type implementing the Error trait.
#[derive(Debug)] struct MyError; impl std::fmt::Display for MyError { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { write!(f, "An error occurred") } } impl std::error::[1] for MyError {{}} fn do_something() -> Result<(), MyError> { Err(MyError) }
Clone or Copy.Err variant.The custom error type must implement the Error trait. Returning Err(MyError) signals an error.
Fill all three blanks to use a Result with map_err to convert error types.
fn parse_number(s: &str) -> Result<i32, String> {
s.parse::<i32>()
.map_err(|[1]| [2]::from(format!("Parse error: {}", [3])))
}std::io::Error.The closure argument e is used to create a new String error message with format!.
