Start with the idea
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.
Keep learning, for free
The rest of this lesson is waiting for you.
Create a free account to read the complete explanation, see the infographic, explore the code, and try the exercises. All 742 lessons and algorithm steps are included.
No payment details. Your account opens the complete Academy.