</>
Skip to content
Rust lessons (33/43)

Rust — Error Handling

Result<T, E>

use std::fs;

fn read_file(path: &str) -> Result<String, std::io::Error> {
    fs::read_to_string(path)
}

fn main() {
    match read_file("file.txt") {
        Ok(content) => println!("{}", content),
        Err(e) => println!("Error: {}", e),
    }
}

Option<T>

fn find_user(id: u32) -> Option<String> {
    if id == 1 {
        Some(String::from("Alice"))
    } else {
        None
    }
}

fn main() {
    match find_user(1) {
        Some(name) => println!("Found: {}", name),
        None => println!("User not found"),
    }
}

? operator

use std::fs;
use std::io;

fn read_config() -> Result<String, io::Error> {
    let content = fs::read_to_string("config.txt")?;
    Ok(content)
}

Custom error types

use std::fmt;

#[derive(Debug)]
enum AppError {
    NotFound(String),
    ParseError(String),
    IoError(std::io::Error),
}

impl fmt::Display for AppError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            AppError::NotFound(s) => write!(f, "Not found: {}", s),
            AppError::ParseError(s) => write!(f, "Parse error: {}", s),
            AppError::IoError(e) => write!(f, "IO error: {}", e),
        }
    }
}

impl From<std::io::Error> for AppError {
    fn from(e: std::io::Error) -> Self {
        AppError::IoError(e)
    }
}

Unwrap and expect

fn main() {
    // unwrap: panics on None/Err
    let s = Some("hello").unwrap();

    // expect: custom panic message
    let n: Option<i32> = None;
    // n.expect("should have a value"); // Panics with custom message

    // unwrap_or: default value
    let val = n.unwrap_or(0);
    println!("{}", val);
}

Mini Practice

Write Rust code that:

  1. Returns Result from a function
  2. Uses the ? operator for error propagation
  3. Creates a custom error type
  4. Uses unwrap_or for default values

Up Next

In the next lesson, you'll learn about Collections — Vec, HashMap, and more.

Related Topics

Frequently Asked Questions about Error Handling

What is Error Handling in Rust?

Error Handling is a fundamental concept in Rust. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Error Handling?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Error Handling.

Why is Error Handling important in Rust?

Error Handling is essential for Rust development. Understanding this concept will help you write better code and solve real-world problems more effectively.