Rust Error Handling — Result, Option, Panic, and Error Propagation with ? Operator
DodaTech
Updated 2026-06-28
1 min read
In this tutorial, you will learn about Rust Error Handling. We cover key concepts, practical examples, and best practices to help you master this topic.
Rust error handling uses Result for recoverable errors, Option for optional values, panic! for unrecoverable, and ? operator for propagation.
What You'll Learn
- Result and Option types
- panic! for unrecoverable errors
- ? operator for propagation
- Custom error types
Why It Matters
Error handling is critical for reliable software. DodaZIP uses Result for all I/O operations. Firefox uses custom error types for browser functionality.
Real-World Use
File I/O, network requests, data Parsing, configuration validation, API error responses.
use std::fs::File;
use std::io::{self, Read};
fn read_username(path: &str) -> Result<String, io::Error> {
let mut file = File::open(path)?;
let mut username = String::new();
file.read_to_string(&mut username)?;
Ok(username.trim().to_string())
}
fn find_user(id: u32) -> Option<String> {
match id {
1 => Some(String::from("Alice")),
2 => Some(String::from("Bob")),
_ => None,
}
}
#[derive(Debug)]
enum AppError {
NotFound(String),
PermissionDenied,
IoError(io::Error),
}
fn process_file(path: &str) -> Result<String, AppError> {
let content = read_username(path).map_err(AppError::IoError)?;
if content.is_empty() {
return Err(AppError::NotFound(path.to_string()));
}
Ok(content)
}
fn main() {
match read_username("user.txt") {
Ok(name) => println!("Username: {}", name),
Err(e) => eprintln!("Error: {}", e),
}
match find_user(1) {
Some(name) => println!("Found: {}", name),
None => println!("User not found"),
}
// panic! for unrecoverable errors
let v = vec![1, 2, 3];
// v[99]; // Would panic
}
← Previous
Rust Enums and Pattern Matching — Defining Enums, Options, Results, and Match Patterns
Next →
Rust Generics — Generic Functions, Structs, Enums, and Trait Bounds
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro