You are viewing a free preview of this lesson.
Subscribe to unlock all 10 lessons in this course and every other course on LearningBro.
Rust takes a unique approach to error handling — there are no exceptions. Instead, Rust uses the Result<T, E> enum for recoverable errors and panic! for unrecoverable errors. This makes error handling explicit and impossible to ignore.
| Kind | Mechanism | Example |
|---|---|---|
| Unrecoverable | panic! macro | Index out of bounds, corrupted state |
| Recoverable | Result<T, E> enum | File not found, invalid input, network timeout |
Most errors in Rust are recoverable and should use Result.
When something goes catastrophically wrong:
fn main() {
panic!("crash and burn!");
}
When a panic! occurs:
panic! explicitly.unwrap() on a None or ErrTip: Set the environment variable
RUST_BACKTRACE=1to see a full backtrace when a panic occurs.
The Result enum represents either success or failure:
enum Result<T, E> {
Ok(T), // success, containing a value of type T
Err(E), // failure, containing an error of type E
}
use std::fs::File;
fn main() {
let file_result = File::open("hello.txt");
let file = match file_result {
Ok(f) => f,
Err(e) => panic!("Could not open file: {e}"),
};
}
use std::fs::File;
use std::io::ErrorKind;
fn main() {
let file = match File::open("hello.txt") {
Ok(f) => f,
Err(error) => match error.kind() {
ErrorKind::NotFound => match File::create("hello.txt") {
Ok(f) => f,
Err(e) => panic!("Could not create file: {e}"),
},
other => panic!("Could not open file: {other:?}"),
},
};
}
Returns the value inside Ok or panics on Err:
let file = File::open("hello.txt").unwrap();
// Panics with a generic message if the file does not exist
Like unwrap, but with a custom panic message:
let file = File::open("hello.txt")
.expect("hello.txt should be included in this project");
Tip: Prefer
expectoverunwrap— the custom message helps during debugging. In production code, prefer proper error handling over both.
The ? operator propagates errors, making error handling concise:
use std::fs::File;
use std::io::{self, Read};
fn read_username_from_file() -> Result<String, io::Error> {
let mut file = File::open("username.txt")?; // returns Err if it fails
let mut username = String::new();
file.read_to_string(&mut username)?; // returns Err if it fails
Ok(username)
}
The ? operator:
Ok(v), unwraps and returns vErr(e), returns Err(e) from the enclosing functionFrom traitSubscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.