0
0
Rustprogramming~20 mins

Error handling best practices in Rust - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Rust Error Handling Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the output of this Rust code using Result?

Consider this Rust code that tries to parse a number from a string and handle errors:

fn parse_number(s: &str) -> Result {
    s.parse::().map_err(|_| "Parse error".to_string())
}

fn main() {
    match parse_number("42") {
        Ok(n) => println!("Number: {}", n),
        Err(e) => println!("Error: {}", e),
    }
}

What will this program print when run?

Rust
fn parse_number(s: &str) -> Result<i32, String> {
    s.parse::<i32>().map_err(|_| "Parse error".to_string())
}

fn main() {
    match parse_number("42") {
        Ok(n) => println!("Number: {}", n),
        Err(e) => println!("Error: {}", e),
    }
}
ANumber: 0
BError: Parse error
CNumber: 42
DCompilation error
Attempts:
2 left
💡 Hint

Think about what parse::() returns when given a valid number string.

Predict Output
intermediate
2:00remaining
What error does this Rust code produce?

Look at this Rust code snippet:

fn main() {
    let v = vec![1, 2, 3];
    println!("{}", v[10]);
}

What happens when you run this program?

Rust
fn main() {
    let v = vec![1, 2, 3];
    println!("{}", v[10]);
}
AIndex out of bounds panic at runtime
BCompilation error: index out of bounds
CPrints 10
DPrints 0
Attempts:
2 left
💡 Hint

Think about how Rust handles accessing vector elements with an invalid index.

🧠 Conceptual
advanced
2:00remaining
Which Rust error handling practice is recommended for library code?

When writing a Rust library, which error handling approach is best practice?

AUse <code>panic!</code> to stop execution on errors
BReturn <code>Result</code> types to allow caller to handle errors
CIgnore errors and return default values
DUse <code>unwrap()</code> to simplify code
Attempts:
2 left
💡 Hint

Think about how libraries should behave to be flexible for users.

Predict Output
advanced
2:00remaining
What is the output of this Rust code using ? operator?

Consider this Rust function:

fn get_first_char(s: &str) -> Result {
    let c = s.chars().next().ok_or("Empty string".to_string())?;
    Ok(c)
}

fn main() {
    match get_first_char("") {
        Ok(c) => println!("First char: {}", c),
        Err(e) => println!("Error: {}", e),
    }
}

What will this program print?

Rust
fn get_first_char(s: &str) -> Result<char, String> {
    let c = s.chars().next().ok_or("Empty string".to_string())?;
    Ok(c)
}

fn main() {
    match get_first_char("") {
        Ok(c) => println!("First char: {}", c),
        Err(e) => println!("Error: {}", e),
    }
}
APanic at runtime
BFirst char:
CCompilation error
DError: Empty string
Attempts:
2 left
💡 Hint

What does ok_or do when the iterator is empty?

🔧 Debug
expert
3:00remaining
Why is this Rust code problematic?

Examine this Rust code snippet:

fn read_file() -> Result {
    let content = std::fs::read_to_string("file.txt").unwrap();
    Ok(content)
}

Why is this not recommended when used in a function that returns Result?

Rust
fn read_file() -> Result<String, std::io::Error> {
    let content = std::fs::read_to_string("file.txt").unwrap();
    Ok(content)
}
AThe function should propagate errors using the <code>?</code> operator instead of <code>unwrap()</code>
BUsing <code>unwrap()</code> causes a panic and is not allowed in functions returning Result
CThe <code>read_to_string</code> function does not return a Result
DThe function must return <code>Option</code> instead of <code>Result</code>
Attempts:
2 left
💡 Hint

Think about how to properly propagate errors in functions returning Result.