0
0
Rustprogramming~10 mins

Error handling best practices in Rust - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to return a Result type from the function.

Rust
fn divide(a: f64, b: f64) -> [1] {
    if b == 0.0 {
        Err("Cannot divide by zero")
    } else {
        Ok(a / b)
    }
}
Drag options to blanks, or click blank then click option'
AResult<f64, &str>
BOption<f64>
Cf64
Dbool
Attempts:
3 left
💡 Hint
Common Mistakes
Using Option instead of Result when you want to provide error details.
Returning just f64 without error handling.
2fill in blank
medium

Complete the code to propagate errors using the ? operator.

Rust
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)
}
Drag options to blanks, or click blank then click option'
A.unwrap()
B.ok()
C?
D.expect("error")
Attempts:
3 left
💡 Hint
Common Mistakes
Using .unwrap() which panics on error instead of propagating it.
Using .ok() which converts to Option and loses error info.
3fill in blank
hard

Fix the error in the match expression to handle both Ok and Err variants.

Rust
match result [1]{
    Ok(value) => println!("Value: {}", value),
    Err(e) => println!("Error: {}", e),
}
Drag options to blanks, or click blank then click option'
Awith
Bin
C=>
D{
Attempts:
3 left
💡 Hint
Common Mistakes
Using '=>' after match instead of braces.
Using 'in' or 'with' which are invalid here.
4fill in blank
hard

Fill in the blank to create a custom error type implementing the Error trait.

Rust
#[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)
}
Drag options to blanks, or click blank then click option'
AError
BClone
CDebug
DCopy
Attempts:
3 left
💡 Hint
Common Mistakes
Implementing the wrong trait like Clone or Copy.
Forgetting to return Err variant.
5fill in blank
hard

Fill all three blanks to use a Result with map_err to convert error types.

Rust
fn parse_number(s: &str) -> Result<i32, String> {
    s.parse::<i32>()
        .map_err(|[1]| [2]::from(format!("Parse error: {}", [3])))
}
Drag options to blanks, or click blank then click option'
Ae
BString
Dstd::io::Error
Attempts:
3 left
💡 Hint
Common Mistakes
Using the wrong variable name in the closure.
Using an unrelated error type like std::io::Error.