1. What Is Error Handling?
Error handling means detecting problems in a program and deciding what to do when they occur.
For example, consider a program that divides two numbers.
This program attempts to divide a number by zero. Integer division by zero causes a runtime panic.
Rust provides different ways to handle such situations safely.
The two major categories of errors in Rust are:
- Unrecoverable errors
- Recoverable errors
2. Unrecoverable Errors – panic!
An unrecoverable error is a problem from which the program cannot reasonably continue.
Rust provides the panic! macro to stop execution when such a problem occurs.
Syntax:
Example:
Output:
The last println! statement will not execute.
When should you use panic!?
Use panic! when:
- The program reaches an impossible state.
- Continuing execution would be unsafe.
- A programming error has occurred that should not be silently ignored.
Do not use panic! for ordinary user input errors that your program can handle.
3. Recoverable Errors
A recoverable error is a problem that your program can handle without stopping completely.
For example:
- A file is missing.
- A user enters an invalid number.
- A requested record is not found.
Rust commonly uses two types for handling these situations:
Option<T>Result<T, E>
4. Understanding Option<T>
Sometimes a function may return a value, or it may have no value to return.
Rust uses Option<T> for this situation.
It has two variants:
Variant | Meaning |
|---|---|
| A value is available |
| No value is available |
Example:
Output:
Another example:
Output:
Using match with Option
Output:
Using if let with Option
If you only want to handle one variant, you can use if let.
Output:
5. Understanding Result<T, E>
Result<T, E> is used when an operation can either succeed or fail.
It has two variants:
Variant | Meaning |
|---|---|
| Operation successful |
| Operation failed |
Here:
Trepresents the success value type.Erepresents the error type.
Example:
Output:
Now try:
Output:
The program does not panic because we handled the error using Result.
6. Understanding the ? Operator
The ? operator is used to propagate errors.
It makes error handling shorter and cleaner.
Consider this example:
Explanation:
If the file is read successfully, the content is returned.
If reading fails, the error is returned immediately from read_file().
The ? operator does not automatically handle or print the error. It propagates the error to the calling function.
Important: The function using ? must return a compatible Result or Option type.
7. Understanding unwrap()
The unwrap() method extracts the value from Option or Result.
Example with Option:
Output:
Example with Result:
Output:
What happens if unwrap fails?
This causes a panic because there is no value inside None.
Important: Avoid using unwrap() when an error is reasonably possible in production code. Prefer match, if let, or ? where appropriate.
8. Understanding expect()
expect() works like unwrap(), but allows you to provide a custom panic message.
Example:
This causes a panic with the message:
Difference between unwrap() and expect()
Method | Purpose |
|---|---|
| Extracts a value or panics |
| Extracts a value or panics with your message |
9. Understanding unwrap_or()
Sometimes you want to use a default value if no value is available.
The unwrap_or() method helps with this.
Example:
Output:
Here, because age contains None, Rust uses the default value 18.
You can also use it with Result:
Output:
10. Converting Errors Using map_err()
The map_err() method allows you to transform an error into another error type.
Example:
Output:
Here, the original error message is converted into a new String message.
11. Difference Between Option and Result
Feature | Option<T> | Result<T, E> |
|---|---|---|
Purpose | Represents an optional value | Represents success or failure |
Success variant |
|
|
Other variant |
|
|
Error information | Does not contain an error message | Can contain error information |
Common use | Value may be missing | Operation may fail |
Example:
Use Option when searching for a student:
Use Result when saving student data:
12. Common Mistakes
Mistake | Explanation |
|---|---|
Using | Can cause unexpected panics |
Ignoring | Errors may remain unhandled |
Confusing |
|
Using | The function must return a compatible type |
Using | Prefer recoverable error handling |