Handling Errors
In Rust, there are no exceptions like in Python or JavaScript. Instead, Rust uses two special types to handle situations where something might go wrong: Result and Option.
Option — Maybe There's a Value
Option represents a value that might or might not exist:
An Option is either Some(value) or None. The .get() method on vectors returns an Option because the index might be out of bounds.
Matching on Option
You can use match to handle both cases:
unwrap and expect
If you're sure a value exists, you can use .unwrap() to get it directly. But if it's None, your program will crash!
.expect("message") does the same but shows your custom message if it crashes:
unwrap_or — Safe Default
Instead of crashing, you can provide a default value:
Result — Success or Error
Result is for operations that might fail. It's either Ok(value) or Err(error):
A common example is parsing strings to numbers:
Matching on Result
The ? Operator
In functions that return Result, you can use ? to pass errors up automatically:
The ? means: "If this is Ok, unwrap it. If it's Err, return the error immediately."
Summary
| Concept | What it does |
|---|---|
Option<T> | A value that might be Some(T) or None |
Result<T, E> | A result that's Ok(T) or Err(E) |
.unwrap() | Gets the value or crashes |
.expect("msg") | Gets the value or crashes with a message |
.unwrap_or(&default) | Gets the value or uses a default |
match on Option/Result | Handle each case explicitly |
? operator | Pass errors up to the caller |
Now let's practice handling errors!