Bird
Raised Fist0
Rustprogramming~10 mins

Error handling best practices in Rust - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Error handling best practices
Start Function
↓
Try Operation
↓
Operation Success?
No→Handle Error
↓
Return or Log Error
↓
Continue with Result
↓
End Function
This flow shows how Rust code tries an operation, checks if it succeeded, handles errors if any, and continues safely.
Execution Sample
Rust
fn read_file() -> Result<String, std::io::Error> {
    let content = std::fs::read_to_string("file.txt")?;
    Ok(content)
}
This function tries to read a file and returns its content or an error using Rust's Result type.
Execution Table
StepActionEvaluationResult
1Call read_file()Starts functionFunction begins
2Attempt std::fs::read_to_string("file.txt")File exists?Success or Error
3If successContent readcontent = file text
4Return Ok(content)Wrap content in OkResult::Ok(content)
5If errorError returned by read_to_stringFunction returns Err(error)
6Caller handles ResultMatch on ResultProcess content or handle error
💡 Function ends by returning Result with Ok or Err depending on file read success
Variable Tracker
VariableStartAfter Step 3Final
contentuninitializedfile text if successfile text or none if error
Key Moments - 3 Insights
Why do we use Result instead of panicking on error?
Using Result lets the caller decide how to handle errors safely, as shown in step 6 of the execution_table, instead of crashing the program.
What does the ? operator do in step 2?
The ? operator returns early with Err if the operation fails, as seen in step 5, simplifying error propagation.
How do we handle errors after calling read_file()?
The caller matches on the Result to handle success or error, shown in step 6, allowing graceful recovery or logging.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what happens at step 5 if the file does not exist?
AThe function returns Ok with empty content
BThe function returns Err with the error
CThe function panics and stops
DThe function retries reading the file
💡 Hint
Check step 5 in execution_table where error causes function to return Err
At which step does the ? operator cause early return on error?
AStep 2
BStep 3
CStep 4
DStep 6
💡 Hint
Look at step 2 where the file read is attempted and ? is applied
If the file is read successfully, what is the final value of 'content' variable?
Auninitialized
Bempty string
Cfile text content
Derror message
💡 Hint
See variable_tracker row for 'content' after step 3 and final
Concept Snapshot
Rust error handling uses the Result<T, E> type.
Use the ? operator to propagate errors simply.
Return Ok(value) on success, Err(error) on failure.
Caller matches on Result to handle errors safely.
Avoid panics for recoverable errors.
This leads to robust, clear error management.
Full Transcript
This visual execution shows how Rust handles errors using the Result type. The function read_file tries to read a file. If successful, it returns Ok with the file content. If it fails, it returns Err with the error. The ? operator helps return early on errors. The caller then matches on the Result to decide what to do next. This approach avoids crashes and lets programs handle errors clearly and safely.

Practice

(1/5)
1. What is the primary purpose of using Result in Rust error handling?
easy
A. To convert a string into a number
B. To represent either success or failure of an operation
C. To define a constant value in the program
D. To create a new thread for parallel execution

Solution

  1. Step 1: Understand the role of Result

    Result is an enum used to represent either success (Ok) or failure (Err) in Rust operations.
  2. Step 2: Identify the purpose in error handling

    It helps safely handle errors by forcing the programmer to consider both success and failure cases explicitly.
  3. Final Answer:

    To represent either success or failure of an operation -> Option B
  4. Quick Check:

    Result = success or failure [OK]
Hint: Result means success or error outcome [OK]
Common Mistakes:
  • Confusing Result with threading or constants
  • Thinking Result automatically fixes errors
  • Using Result only for numbers or strings
2. Which of the following is the correct syntax to use the ? operator in a function that returns Result<T, E>?
easy
A. let value = some_function()?;
B. let value = some_function!();
C. let value = some_function();?
D. let value = ?some_function();

Solution

  1. Step 1: Recall the ? operator usage

    The ? operator is placed immediately after a function call that returns a Result to propagate errors easily.
  2. Step 2: Check syntax correctness

    let value = some_function()?; correctly places ? after the function call: some_function()?. Other options misuse the operator placement.
  3. Final Answer:

    let value = some_function()?; -> Option A
  4. Quick Check:

    ? goes right after function call [OK]
Hint: Put ? right after the function call [OK]
Common Mistakes:
  • Placing ? before the function call
  • Using ! instead of ?
  • Adding ? after semicolon
3. What will be the output of this Rust code snippet?
fn divide(a: i32, b: i32) -> Result {
    if b == 0 {
        Err(String::from("division by zero"))
    } else {
        Ok(a / b)
    }
}

fn main() {
    match divide(10, 0) {
        Ok(result) => println!("Result: {}", result),
        Err(e) => println!("Error: {}", e),
    }
}
medium
A. Result: 0
B. Panic at runtime
C. Error: division by zero
D. No output

Solution

  1. Step 1: Analyze the divide function call

    The function is called with b = 0, triggering the error branch returning Err("division by zero").
  2. Step 2: Check the match handling in main

    The Err case prints "Error: division by zero" to the console.
  3. Final Answer:

    Error: division by zero -> Option C
  4. Quick Check:

    Error message prints on zero divisor [OK]
Hint: Check if divisor is zero to get error output [OK]
Common Mistakes:
  • Assuming division returns 0 instead of error
  • Expecting panic instead of handled error
  • Ignoring match arms
4. Identify the error in this Rust code snippet related to error handling:
fn read_file() -> Result {
    let content = std::fs::read_to_string("file.txt");
    Ok(content)
}
medium
A. File path should be a variable, not a string literal
B. Function should return String not Result
C. Using Ok instead of Err
D. Missing ? operator to propagate error

Solution

  1. Step 1: Understand the return type and function call

    The function returns Result<String, std::io::Error>, but read_to_string returns a Result itself.
  2. Step 2: Identify missing error propagation

    The code assigns content as a Result but wraps it again in Ok without handling errors. The ? operator is needed to propagate errors properly.
  3. Final Answer:

    Missing ? operator to propagate error -> Option D
  4. Quick Check:

    Use ? to handle Result errors [OK]
Hint: Use ? to unwrap or propagate Result errors [OK]
Common Mistakes:
  • Wrapping Result inside Ok again
  • Ignoring error propagation
  • Changing return type incorrectly
5. You want to write a function that reads two files and returns the combined content as a String. Which is the best way to handle errors using Result and the ? operator? Choose the correct implementation:
fn read_two_files() -> Result {
    // Option A
    let content1 = std::fs::read_to_string("file1.txt")?;
    let content2 = std::fs::read_to_string("file2.txt")?;
    Ok(content1 + &content2)

    // Option B
    let content1 = std::fs::read_to_string("file1.txt").unwrap();
    let content2 = std::fs::read_to_string("file2.txt").unwrap();
    Ok(content1 + &content2)

    // Option C
    let content1 = std::fs::read_to_string("file1.txt").expect("file1 missing");
    let content2 = std::fs::read_to_string("file2.txt").expect("file2 missing");
    Ok(content1 + &content2)

    // Option D
    let content1 = std::fs::read_to_string("file1.txt");
    let content2 = std::fs::read_to_string("file2.txt");
    Ok(content1.unwrap() + &content2.unwrap())
}
hard
A. Use ? operator to propagate errors cleanly
B. Use unwrap() which panics on error
C. Use expect() which panics with message
D. Call unwrap() on Result without error handling

Solution

  1. Step 1: Understand error propagation best practice

    Using the ? operator propagates errors to the caller without panicking, making the function safe and clear.
  2. Step 2: Compare with other options

    The other options use unwrap() or expect(), which cause the program to panic on error, not recommended for robust error handling.
  3. Final Answer:

    Use ? operator to propagate errors cleanly -> Option A
  4. Quick Check:

    ? propagates errors safely [OK]
Hint: Use ? to avoid panics and propagate errors [OK]
Common Mistakes:
  • Using unwrap or expect causing panics
  • Not propagating errors properly
  • Ignoring error handling for multiple calls
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