Skip to main content
Brave Programmer Logo

BraveProgrammer

BraveProgrammer

HomeProjectsBlogsCoursesLessonsAbout

Site footer

BraveProgrammer

Free coding courses, practical tutorials, and real projects from BraveProgrammer. Learn web development with React, Next.js, and TypeScript.

Navigation

  • Home
  • Projects
  • Blogs
  • Courses

Resources

  • About
  • Lessons
  • Teach on BraveProgrammer

© 2026 BraveProgrammer. All rights reserved.

Error Handling with Result | Rust Fundamentals lesson | BraveProgrammer
  1. Courses
  2. /
  3. Rust Fundamentals

Lesson 19 of 50

·rust

Error Handling with Result

20 minutes

Course progress38%

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
// Question mark propagates errors
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:

// Without ?: verbose
fn process() -> Result<i32, String> {
    let val = match risky_operation() {
        Ok(v) => v,
        Err(e) => return Err(e),
    };
    Ok(val * 2)
}

// With ?: concise
fn process() -> Result<i32, String> {
    let val = risky_operation()?;  // Return early if Err
    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

  1. Propagate with ?: Return errors to caller
  2. Handle with match: Explicitly handle each case
  3. Use unwrap_or: Provide sensible defaults
  4. 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
Previous lessonError Handling with OptionContinue to lesson 20Panic and UnwindingBack to Rust Fundamentals curriculum