0
0
Rustprogramming~5 mins

Propagating errors with ? in Rust

Choose your learning style9 modes available
Introduction

The ? operator helps you quickly pass errors up to the caller without writing extra code. It makes error handling simple and clean.

When you call a function that might fail and want to stop if it does.
When you want to avoid writing many <code>match</code> or <code>if let</code> blocks for errors.
When you want your function to return an error if something inside it fails.
When you want to keep your code easy to read and understand.
When you want to chain multiple fallible operations smoothly.
Syntax
Rust
fn example() -> Result<Type, Error> {
    let value = some_fallible_function()?;
    // use value
    Ok(value)
}

The function must return a Result type to use ?.

The ? operator returns the error immediately if the result is Err.

Examples
This reads a file and returns its content or an error if reading fails.
Rust
fn read_file() -> Result<String, std::io::Error> {
    let content = std::fs::read_to_string("file.txt")?;
    Ok(content)
}
This tries to convert a string to a number and returns an error if it can't.
Rust
fn parse_number(s: &str) -> Result<i32, std::num::ParseIntError> {
    let num = s.parse::<i32>()?;
    Ok(num)
}
Sample Program

This program tries to open a file called username.txt and read its content. If any step fails, the error is passed up using ? and handled in main.

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

fn read_username() -> 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() {
        Ok(name) => println!("Username: {}", name),
        Err(e) => println!("Error reading username: {}", e),
    }
}
OutputSuccess
Important Notes

The ? operator only works in functions that return Result or Option.

Using ? keeps your code short and easy to follow.

Summary

The ? operator quickly returns errors from a function.

It works only in functions returning Result or Option.

It helps write clean and readable error handling code.