0
0
Rustprogramming~5 mins

Error handling best practices in Rust

Choose your learning style9 modes available
Introduction

Error handling helps your program deal with problems without crashing. It keeps your program safe and user-friendly.

When reading a file that might not exist
When converting user input to a number
When calling a function that might fail
When working with network requests that can time out
Syntax
Rust
use std::result::Result;

fn example() -> Result<i32, String> {
    // code that might fail
    Ok(42)
}

fn main() {
    match example() {
        Ok(value) => println!("Got value: {}", value),
        Err(e) => println!("Error: {}", e),
    }
}

Result is an enum with Ok for success and Err for errors.

Use match to handle both success and error cases clearly.

Examples
Simple example showing how to match on a Result to get the number or print an error.
Rust
use std::result::Result;

fn main() {
    let result: Result<i32, &str> = Ok(10);

    match result {
        Ok(num) => println!("Number is {}", num),
        Err(msg) => println!("Error: {}", msg),
    }
}
Function returns an error if dividing by zero, otherwise returns the result.
Rust
use std::result::Result;

fn divide(a: i32, b: i32) -> Result<i32, String> {
    if b == 0 {
        Err(String::from("Cannot divide by zero"))
    } else {
        Ok(a / b)
    }
}

fn main() {
    match divide(10, 0) {
        Ok(res) => println!("Result: {}", res),
        Err(e) => println!("Error: {}", e),
    }
}
Example showing how to handle file opening errors using Result.
Rust
use std::fs::File;
use std::result::Result;

fn open_file() -> Result<File, std::io::Error> {
    File::open("hello.txt")
}

fn main() {
    match open_file() {
        Ok(file) => println!("File opened successfully"),
        Err(e) => println!("Failed to open file: {}", e),
    }
}
Sample Program

This program tries to read a username from a file. It uses Result and the ? operator to handle errors simply. If the file is missing or unreadable, it prints an error message.

Rust
use std::fs::File;
use std::io::{self, Read};
use std::result::Result;

fn read_username_from_file() -> Result<String, io::Error> {
    let mut file = File::open("username.txt")?;
    let mut username = String::new();
    file.read_to_string(&mut username)?;
    Ok(username)
}

fn main() {
    match read_username_from_file() {
        Ok(name) => println!("Username: {}", name),
        Err(e) => println!("Error reading username: {}", e),
    }
}
OutputSuccess
Important Notes

Use the ? operator to return errors quickly and keep code clean.

Always handle both Ok and Err cases to avoid crashes.

Use meaningful error messages to help users and developers understand what went wrong.

Summary

Error handling keeps your program safe and clear.

Use Result and match to handle success and failure.

The ? operator helps write cleaner error-handling code.