Robust Error Handling with `Result`
Implement idiomatic error handling using the `Result` enum, `?` operator, and custom error types for resilient applications.
Robust Error Handling with `Result` is a free Learn Rust Coding lesson on CoddyKit — lesson 3 of 3. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Learn Rust Coding learning path, one of 3 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Handling Errors in Rust
Errors are a part of programming. In Rust, we distinguish between two main types: recoverable and unrecoverable errors.
- Unrecoverable errors usually signal bugs, causing the program to stop with
panic!. - Recoverable errors mean something went wrong but can be handled, like a file not found.
Rust helps you deal with recoverable errors gracefully.
`panic!` vs `Result`
When an unrecoverable error occurs, Rust calls the panic! macro. This unwinds the stack and exits your program, usually printing an error message.
For recoverable errors, Rust uses the Result enum. This enum tells you if an operation succeeded (Ok) or failed (Err), letting your program decide what to do next.
The `Result` Enum
The Result enum is defined conceptually as:
enum Result<T, E> {
Ok(T),
Err(E),
}
Trepresents the type of value returned on success.Erepresents the type of error returned on failure.
It's a powerful way to explicitly state that a function might fail.
Matching on `Result`
The most common way to handle a Result is using a match expression. This allows you to execute different code blocks based on whether the Result is Ok or Err.
Try running this example that attempts to parse a number:
fn parse_and_add(text: &str) -> Result<i32, std::num::ParseIntError> {
text.parse::<i32>()
}
fn main() {
let num_str = "123";
let result = parse_and_add(num_str);
match result {
Ok(num) => println!("Parsed number: {}", num),
Err(e) => println!("Error parsing: {}", e),
}
let bad_str = "abc";
let bad_result = parse_and_add(bad_str);
match bad_result {
Ok(num) => println!("Parsed number: {}", num),
Err(e) => println!("Error parsing: {}", e),
}
}Unwrapping Results (Carefully!)
Sometimes you might be certain an operation won't fail, or you want your program to crash if it does. Methods like unwrap() and expect() extract the Ok value.
unwrap(): Returns theOkvalue or panics if it'sErr.expect("message"): Same asunwrap()but lets you provide a custom panic message.
Use these sparingly, mainly in tests or when failure is truly unrecoverable.
Introducing the `?` Operator
Writing match statements for every Result can get repetitive. The ? operator provides a concise shortcut for error propagation.
When placed after an expression that returns a Result, ? does two things:
- If the
ResultisErr, it immediately returns theErrfrom the current function. - If the
ResultisOk, it unwraps theOkvalue and continues execution.
`?` Operator in Action
The ? operator makes functions that might fail much cleaner to write. Remember, the function using ? must itself return a Result (or Option).
Observe how ? simplifies error handling in this file reading example:
use std::fs::File;
use std::io::{self, Read};
fn read_username_from_file() -> Result<String, io::Error> {
let mut f = File::open("hello.txt")?; // Propagates error if file not found
let mut s = String::new();
f.read_to_string(&mut s)?; // Propagates error if read fails
Ok(s)
}
fn main() {
// Create a dummy file for the example to work
// In a real scenario, this file might not exist
std::fs::write("hello.txt", "CoddyKit User").unwrap();
match read_username_from_file() {
Ok(username) => println!("Username: {}", username),
Err(e) => println!("Error reading username: {}", e),
}
// Clean up the dummy file
std::fs::remove_file("hello.txt").unwrap();
}Custom Error Types
Sometimes, built-in error types aren't specific enough. You can define your own custom error types using enums to represent different failure modes of your application.
This makes your error messages clearer and allows callers to handle specific errors differently.
A common pattern is to create an enum that lists all possible errors a function or module can produce.
Making `?` Work with Custom Errors
For the ? operator to automatically convert a lower-level error (like io::Error) into your custom error type, your custom error enum must implement the From trait for that lower-level error.
This tells Rust how to convert one error type into another, making error propagation seamless.
use std::io;
use std::fs::File;
use std::io::Read;
#[derive(Debug)]
enum MyError {
Io(io::Error),
Parse(std::num::ParseIntError)
}
impl From<io::Error> for MyError {
fn from(error: io::Error) -> Self {
MyError::Io(error)
}
}
impl From<std::num::ParseIntError> for MyError {
fn from(error: std::num::ParseIntError) -> Self {
MyError::Parse(error)
}
}
fn read_config(path: &str) -> Result<i32, MyError> {
let mut file = File::open(path)?; // io::Error converted to MyError::Io
let mut contents = String::new();
file.read_to_string(&mut contents)?; // io::Error converted to MyError::Io
let value = contents.trim().parse::<i32>()?; // ParseIntError converted to MyError::Parse
Ok(value)
}
fn main() {
// Create a dummy file for the example
std::fs::write("config.txt", "123").unwrap();
match read_config("config.txt") {
Ok(val) => println!("Config value: {}", val),
Err(e) => println!("Failed to read config: {:?}", e),
}
std::fs::remove_file("config.txt").unwrap(); // Clean up
// Example with a non-existent file
match read_config("non_existent.txt") {
Ok(val) => println!("Config value: {}", val),
Err(e) => println!("Failed to read config: {:?}", e),
}
}Check Your Understanding
Consider the following Rust code snippet. What will be the output if the file data.txt does NOT exist?
Recap: Robust Error Handling
You've mastered robust error handling in Rust!
ResultEnum: Distinguishes betweenOk(T)for success andErr(E)for failure.match: The fundamental way to handleResultvariants.?Operator: A powerful shortcut for propagatingErrvalues up the call stack.- Custom Errors: Define your own error types using enums for clarity and specific handling.
FromTrait: Enables seamless conversion of lower-level errors into your custom error types when using?.
Next, explore advanced type system features!
Frequently asked questions
Is the “Robust Error Handling with `Result`” lesson free?
Yes — the full text of “Robust Error Handling with `Result`” is free to read here on the web, and the Learn Rust Coding course includes 3 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Learn Rust Coding course, upgrade to CoddyKit PRO.
What will I learn in “Robust Error Handling with `Result`”?
Implement idiomatic error handling using the `Result` enum, `?` operator, and custom error types for resilient applications. You practise Learn Rust Coding with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Learn Rust Coding?
No prior experience is required. Learn Rust Coding on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 3, so you can start here or from the beginning and move at your own pace.
How long does the “Robust Error Handling with `Result`” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Learn Rust Coding lesson?
Yes. Every Learn Rust Coding lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Organizing Code with Modules
- Managing Dependencies with Crates
- Robust Error Handling with `Result`