Skip to main content Error Handling with Result | Rust Fundamentals lesson | BraveProgrammerError Handling with Result
20 minutes
Error Handling with Result
Result<T, E> represents operations that can succeed (Ok) or fail (Err). It's the standard for fallible operations in Rust.
The Result Type
enum Result<T, E> {
Ok(T),
Err(E),
}
Reading Files with Result
std::fs::File;
std::io::{, Read};
(path: &) <, io::Error> {
= File::(path)?;
= ::();
file.(& contents)?;
(contents)
}
() {
(\
use
use
self
fn
read_file
str
->
Result
String
let
mut
file
open
let
mut
contents
String
new
read_to_string
mut
Ok
fn
main
match
read_file
"data.txt\") {
Ok(text) => println!(\"File contents: {}\", text),
Err(e) => eprintln!(\"Error reading file: {}\", e),
}
}
The Question Mark Operator
The ? operator automatically propagates errors:
fn process() -> Result<i32, String> {
let val = match risky_operation() {
Ok(v) => v,
Err(e) => return Err(e),
};
Ok(val * 2)
}
fn process() -> Result<i32, String> {
let val = risky_operation()?;
Ok(val * 2)
}
fn risky_operation() -> Result<i32, String> {
Ok(42)
}
Result Methods
fn main() {
let x: Result<i32, String> = Ok(5);
let y: Result<i32, String> = Err(String::from(\"error\"));
// Check state
println!(\"x.is_ok(): {}\", x.is_ok()); // true
println!(\"y.is_err(): {}\", y.is_err()); // true
// Extract with unwrap (panics if Err)
let val = x.unwrap(); // 5
// let bad = y.unwrap(); // panics!
// Safe extraction with default
let val2 = y.unwrap_or(0); // 0
let val3 = y.unwrap_or_else(|e| -1); // -1
// Transform values
let doubled = x.map(|n| n * 2); // Ok(10)
let error_msg = y.map_err(|e| format!(\"Error: {}\", e)); // Err(...)
// Chain operations
x.and_then(|n| Ok(n * 2))
.and_then(|n| Ok(n + 1))
.map(|n| println!(\"Result: {}\", n));
}
Custom Error Types
#[derive(Debug)]
enum ParseError {
InvalidFormat,
Overflow,
}
fn parse_number(s: &str) -> Result<i32, ParseError> {
if s.is_empty() {
return Err(ParseError::InvalidFormat);
}
s.parse::<i32>().map_err(|_| ParseError::Overflow)
}
fn main() {
match parse_number(\"42\") {
Ok(n) => println!(\"Number: {}\", n),
Err(e) => println!(\"Parse error: {:?}\", e),
}
}
Practical Example: Validation Pipeline
fn validate_age(age: u32) -> Result<(), String> {
if age < 0 {
return Err(String::from(\"Age cannot be negative\"));
}
if age > 150 {
return Err(String::from(\"Age seems unrealistic\"));
}
Ok(())
}
fn validate_email(email: &str) -> Result<(), String> {
if !email.contains('@') {
return Err(String::from(\"Invalid email\"));
}
Ok(())
}
fn register_user(email: &str, age: u32) -> Result<(), String> {
validate_email(email)?;
validate_age(age)?;
println!(\"User registered!\");
Ok(())
}
fn main() {
match register_user(\"user@example.com\", 25) {
Ok(_) => println!(\"Success\"),
Err(e) => println!(\"Registration failed: {}\", e),
}
}
Error Handling Strategies
- Propagate with
?: Return errors to caller
- Handle with
match: Explicitly handle each case
- Use
unwrap_or: Provide sensible defaults
- Custom errors: Define domain-specific error types
Result vs Option
- Option: When value may not exist
- Result: When operation may fail with an error
Both enable safe, explicit error handling.
Make it stickPractice what you've learned1 quiz · 1 practical test · Optional activities from Rust FundamentalsBrowse activities