Rust encourages you to decide early whether a failure should be handled or should stop the program. Use Option when a value may be missing, and Result when an operation may succeed or fail with useful error information. For unexpected situations that you cannot reasonably recover from, panic is available, but most real code should prefer recoverable errors and clear propagation. The goal is not to make errors complicated; it is to make failure paths explicit, predictable, and easier to reason about.
Rust Error Handling Made Clear
Learn Option, Result, panic, and ? with practical patterns for handling failures in beginner-friendly Rust code.
Start LearningA simple way to think about errors
Core Rust error-handling patterns
Option for missing values
Use Option when a result may legitimately be absent. It gives you a clear way to represent “something” or “nothing” without guessing or relying on sentinel values.
Result for recoverable failures
Use Result when an operation can fail and you want to know why. This is the standard choice for errors you may want to handle, report, or pass upward.
Match success and failure
Matching lets you handle each case explicitly. You can write separate paths for success, missing values, or errors so your code stays readable and intentional.
Use the question mark operator
The ? operator is a concise way to return errors upward when you do not want to handle them immediately. It keeps straightforward code compact while preserving clear failure behavior.
Propagate errors simply
Simple propagation means checking a Result, handling it where it matters, or passing it to the caller when that is the cleaner choice. This keeps your code easy to follow without complex abstractions.
Know when panic fits
panic is for unrecoverable situations or programmer mistakes, not ordinary failure. In beginner code, treat it as a last resort and favor recoverable error handling first.
Common questions about Rust errors
When should I use Option instead of Result?
Use Option when the only question is whether a value exists. Use Result when you need to represent a failure and possibly explain what went wrong.
Is panic ever appropriate?
Yes, but mainly for unrecoverable situations or bugs that should stop execution immediately. For normal application behavior, prefer Result or Option so the program can respond gracefully.
What does the ? operator do?
It lets a function return early if a Result indicates failure. If the operation succeeds, execution continues with the successful value, making error propagation shorter and easier to read.
How does error propagation work in simple code?
You either handle the failure right away with a match or let the caller handle it by returning Result and using ?. This keeps the control flow direct and makes failure cases visible.