Bird
Raised Fist0
Rustprogramming~20 mins

Handling errors with match in Rust - Practice Problems & Coding Challenges

Choose your learning style10 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
Output of match error handling with Result
What is the output of this Rust code when the input string is "42"?
Rust
fn parse_number(input: &str) -> Result<i32, String> {
    match input.parse::<i32>() {
        Ok(num) => Ok(num),
        Err(_) => Err(String::from("Failed to parse number")),
    }
}

fn main() {
    let result = parse_number("42");
    match result {
        Ok(n) => println!("Parsed number: {}", n),
        Err(e) => println!("Error: {}", e),
    }
}
ACompilation error
BError: Failed to parse number
CParsed number: 0
DParsed number: 42
Attempts:
2 left
💡 Hint
The input string "42" can be successfully converted to an integer.
❓ Predict Output
intermediate
2:00remaining
Output when parsing fails in match
What is the output of this Rust code when the input string is "abc"?
Rust
fn parse_number(input: &str) -> Result<i32, String> {
    match input.parse::<i32>() {
        Ok(num) => Ok(num),
        Err(_) => Err(String::from("Failed to parse number")),
    }
}

fn main() {
    let result = parse_number("abc");
    match result {
        Ok(n) => println!("Parsed number: {}", n),
        Err(e) => println!("Error: {}", e),
    }
}
AError: Failed to parse number
BPanic at runtime
CCompilation error
DParsed number: 0
Attempts:
2 left
💡 Hint
The input string "abc" cannot be converted to an integer.
🔧 Debug
advanced
2:00remaining
Identify the error in match arms handling Result
What error does this Rust code produce when compiled?
Rust
fn main() {
    let result: Result<i32, &str> = Err("error");
    match result {
        Ok(num) => println!("Number: {}", num),
        Err(e) => println!("Error: {}", e),
        _ => println!("Unknown case"),
    }
}
ARuntime panic: no matching pattern
BCompilation error: unreachable pattern
CPrints: Error: error
DCompilation error: missing match arm
Attempts:
2 left
💡 Hint
The match arms cover all possible variants of Result already.
❓ Predict Output
advanced
2:00remaining
Output of nested match error handling
What is the output of this Rust code?
Rust
fn divide(a: i32, b: i32) -> Result<i32, String> {
    if b == 0 {
        Err(String::from("Division by zero"))
    } else {
        Ok(a / b)
    }
}

fn main() {
    let result = divide(10, 0);
    match result {
        Ok(val) => println!("Result: {}", val),
        Err(e) => match e.as_str() {
            "Division by zero" => println!("Cannot divide by zero!"),
            _ => println!("Other error: {}", e),
        },
    }
}
ACannot divide by zero!
BOther error: Division by zero
CResult: 0
DCompilation error
Attempts:
2 left
💡 Hint
The error string matches "Division by zero" exactly.
🧠 Conceptual
expert
2:00remaining
Why use match for error handling in Rust?
Which statement best explains why Rust uses match expressions for handling errors with Result types?
ABecause match automatically retries failed operations without extra code.
BBecause match converts all errors into panics by default.
CBecause match forces exhaustive handling of all possible cases, preventing unhandled errors.
DBecause match allows ignoring errors silently without warnings.
Attempts:
2 left
💡 Hint
Think about safety and explicit handling in Rust.

Practice

(1/5)
1. What does the match statement do when used with a Result type in Rust?
easy
A. It ignores errors and continues execution.
B. It automatically fixes errors in the code.
C. It converts the result into a string.
D. It checks if the result is Ok or Err and lets you handle each case.

Solution

  1. Step 1: Understand the purpose of match with Result

    The match statement is used to check the two possible states of a Result: Ok for success and Err for failure.
  2. Step 2: Recognize handling of both cases

    By matching on Ok and Err, you can write code to handle success and error separately, making the program safe and clear.
  3. Final Answer:

    It checks if the result is Ok or Err and lets you handle each case. -> Option D
  4. Quick Check:

    match with Result = handle Ok or Err [OK]
Hint: Remember: match splits Result into Ok or Err cases [OK]
Common Mistakes:
  • Thinking match fixes errors automatically
  • Assuming match converts Result to string
  • Ignoring error cases in match
2. Which of the following is the correct syntax to match a Result<T, E> named res and print "Success" if Ok?
easy
A. match res { Ok => println!("Success"), Err => println!("Error") }
B. match res { Ok(_) => println!("Success"), Err(_) => println!("Error") }
C. match res { Ok(x) println!("Success"), Err(e) println!("Error") }
D. match res { Ok(_) => println!("Error"), Err(_) => println!("Success") }

Solution

  1. Step 1: Check pattern matching syntax

    The correct syntax uses Ok(_) and Err(_) with arrows => to separate patterns from actions.
  2. Step 2: Verify the printed messages

    match res { Ok(_) => println!("Success"), Err(_) => println!("Error") } prints "Success" on Ok and "Error" on Err, which matches the question requirement.
  3. Final Answer:

    match res { Ok(_) => println!("Success"), Err(_) => println!("Error") } -> Option B
  4. Quick Check:

    Correct match syntax = match res { Ok(_) => println!("Success"), Err(_) => println!("Error") } [OK]
Hint: Use arrows => after patterns and parentheses for Ok/Err [OK]
Common Mistakes:
  • Omitting arrows => in match arms
  • Not using parentheses for Ok(_) or Err(_)
  • Swapping success and error messages
3. What will be the output of this Rust code?
let res: Result<i32, &str> = Err("fail");
match res {
    Ok(val) => println!("Value: {}", val),
    Err(e) => println!("Error: {}", e),
}
medium
A. Error: fail
B. Value: 0
C. Value: fail
D. No output

Solution

  1. Step 1: Identify the Result variant

    The variable res is assigned Err("fail"), so it represents an error.
  2. Step 2: Match arms execution

    The match will go to the Err(e) arm and print "Error: fail".
  3. Final Answer:

    Error: fail -> Option A
  4. Quick Check:

    Err variant prints error message [OK]
Hint: Check if Result is Ok or Err to predict output [OK]
Common Mistakes:
  • Confusing Err with Ok variant
  • Expecting value instead of error message
  • Ignoring the match arms
4. Find the error in this Rust code snippet:
let res: Result<i32, &str> = Ok(10);
match res {
    Ok(val) => println!("Value: {}", val),
    Err => println!("Error occurred"),
}
medium
A. Missing parentheses after Err in match arm
B. Missing semicolon after println! macro
C. Ok variant should be Err
D. Result type is incorrect

Solution

  1. Step 1: Check match arm patterns

    In Rust, match arms for Result must pattern match with parentheses, so Err should be Err(_) or Err(e).
  2. Step 2: Identify the syntax error

    The code uses Err without parentheses, which is invalid syntax and causes a compile error.
  3. Final Answer:

    Missing parentheses after Err in match arm -> Option A
  4. Quick Check:

    Err pattern needs parentheses () [OK]
Hint: Always use parentheses for Err(_) or Ok(_) in match [OK]
Common Mistakes:
  • Writing Err without parentheses
  • Confusing semicolon placement
  • Changing Result type unnecessarily
5. You want to write a function that returns Result<i32, String>. Inside, you try to parse a string to an integer. Using match, how do you handle the parsing result to return Ok(number) if successful or Err with a custom message if it fails?
hard
A. match s.parse() { Ok(n) => Err(n), Err(e) => Ok(e.to_string()) }
B. if s.parse().is_ok() { Ok(s.parse().unwrap()) } else { Err("Parse failed") }
C. match s.parse() { Ok(n) => Ok(n), Err(_) => Err(String::from("Parse failed")) }
D. match s.parse() { Ok(n) => n, Err(_) => "Parse failed" }

Solution

  1. Step 1: Understand parse returns Result

    The parse() method returns Result<T, E>, so matching on it lets us handle success and failure.
  2. Step 2: Return matching Result from function

    On Ok(n), return Ok(n) to propagate success. On Err(_), return Err with a custom error message as a String.
  3. Final Answer:

    match s.parse() { Ok(n) => Ok(n), Err(_) => Err(String::from("Parse failed")) } -> Option C
  4. Quick Check:

    Match parse Result to return Ok or custom Err [OK]
Hint: Return Ok(n) on success, Err(custom message) on failure [OK]
Common Mistakes:
  • Swapping Ok and Err returns
  • Returning raw values instead of Result
  • Using string literals instead of String in Err
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard