
Understand it
Result, custom error types, and ? separate expected failure from programmer mistakes. A panic says this should never happen; a Result says the caller has a decision to make — and conflating the two is what makes error handling painful later.
Expected failures should travel through a function's type. Reading a file may fail because it does not exist or cannot be accessed; returning Result<String, std::io::Error> tells the caller that a successful string and a recoverable error are both possible. In the sample, ? returns the I/O error early while leaving the successful path uncluttered. It does not hide the error: the caller must still handle or propagate it.
At the command-line or UI boundary, turn the error into a message with context. “Could not load configuration from settings.toml” is more useful than “file error” because it identifies the attempted operation. Keep the original cause available for diagnostics when possible. A reusable library should avoid panicking for ordinary missing files or invalid input. Reserve panic for violated internal assumptions where the program cannot reasonably continue.
Try calling load with an existing file and a missing one. In the caller, match on Ok(text) and Err(error), print a helpful message, and decide whether to retry or exit. Then introduce a custom error enum for a workflow that can fail in two different ways, such as I/O and parsing. The type should distinguish those cases without forcing every helper to know about the final presentation. Error handling becomes manageable when each layer adds the context it owns and lets the caller make the next decision.
A caller may attach more context with map_err or a custom error type without changing the original low-level fact. That separation keeps errors useful to both programs and people.
Read the code
fn load(
path: &str,
) -> Result<String, std::io::Error> {
let text = std::fs::read_to_string(path)?;
Ok(text)
}The ? operator returns an Err to the caller, which can handle or propagate it.
Practice starter
fn read(path: &str) -> String {
std::fs::read_to_string(path).unwrap()
}Try it
Replace a panic with a Result and propagate it through one caller.
What success looks like: The caller handles the failure without losing its cause.
Check your understanding
What does unwrap() do if this file operation returns Err?
Reveal the answer
- Returns an empty string on failure
- Panics; unwinding or process abort depends on the panic configuration
- Logs a warning and continues with a default
unwrap panics on Err. With unwinding, an appropriate boundary may catch that panic; panic=abort terminates the process. Return Result for expected I/O failures rather than using panic as routine control flow.
Go deeper
Common misconception: “unwrap() hands back a harmless default when a file read fails.”
unwrap() panics on Err. Panic for a bug; Result for a situation the caller can act on, such as a missing file.
- Read the signature:
loadreturnsResult<String, std::io::Error>, so every caller can see that the read may fail. - Apply the ? operator:
read_to_string(path)?unwraps anOkintotext. OnErr, it returns that I/O error fromloadat once. - Reach the success path:
Ok(text)wraps the contents back up, so the caller chooses what to do with either variant.
Transfer challenge: Add a step that parses the text into a u16, with a custom error enum covering I/O and parsing. Predict which ? needs a From impl, then check with the compiler.
Connections
- Testing: Unit and integration tests
- Dependencies: crates.io, SemVer, and features
Learn this lesson with AI
Paste this into Claude, Codex, Cursor or another agent connected to Crabrix Academy. It contains only this lesson’s public details.
I'm learning Rust with Crabrix Academy. Teach me this lesson with the Crabrix Academy tools. Lesson: Error Design (courseId "projects", lessonId "errors") Link: https://crabrix.com/learn/projects/errors/ Goal: Panic for a bug; Result for a situation the caller can act on. Practice: open the starter in the Crabrix Playground (https://crabrix.com/playground/?lesson=projects/errors) and I will write the code there. Explain it step by step for my level, let me write the code myself, give hints before any solution, and do not mark anything as passed: only Crabrix checks do that.