Rust•Error Handling
Rust Error Handling: Result, Option, and the Question Mark (?) Operator
Rust has no exceptions; errors are explicit return values propagated cleanly using the ? operator.
Syntax
fn task() -> Result<T, Error> {
let val = subtask()?;
Ok(val)
}
Parameters & Values
Key components and acceptable values for this structure:
| Parameter | Type | Description |
|---|---|---|
| ? | Operator | Unwraps Ok value or returns Err early from enclosing function. |
Ready-to-Run Code Example
Executable in CompilraRun this complete, working example directly without installing Rust locally:
fn safe_divide(a: f64, b: f64) -> Result<f64, String> {
if b == 0.0 {
return Err(String::from("Division by zero error"));
}
Ok(a / b)
}
fn run_calculations() -> Result<f64, String> {
// ? operator unwraps or returns Err early
let step1 = safe_divide(100.0, 4.0)?;
let step2 = safe_divide(step1, 5.0)?;
Ok(step2)
}
fn main() {
match run_calculations() {
Ok(res) => println!("Calculation Result: {}", res),
Err(e) => println!("Error encountered: {}", e),
}
match safe_divide(50.0, 0.0) {
Ok(res) => println!("Result: {}", res),
Err(e) => println!("[CAUGHT] Handled error cleanly: {}", e),
}
}Expected Output:
Calculation Result: 5 [CAUGHT] Handled error cleanly: Division by zero error
How It Works: Step-by-Step
- Lines 1-6: safe_divide returns Result<f64, String> with Ok or Err.
- Lines 8-13: ? operator bubbles errors up early without verbose match boilerplate.
Key Concepts
- The ? operator provides concise error propagation.
- Panic! is reserved only for unrecoverable bugs; Result handles expected failures.
Common Mistake: Using ? in a function that does not return Result or Option
? can only be used inside functions whose return type is compatible with what is returned.
❌ Incorrect
fn main() { let x = safe_divide(10.0, 2.0)?; } // Error: main returns ()✅ Correct
fn main() -> Result<(), String> { let x = safe_divide(10.0, 2.0)?; Ok(()) }Related Rust Tutorials & Compiler
Rust Concurrency: Threads and Channels (std::sync::mpsc)
Fearless concurrency in Rust with thread::spawn and mpsc message-passing channels.
Rust Tuples, Enums, and the Option & Result Types
Master algebraic enums, Option<T> (null replacement), and Result<T, E> in Rust.
Rust Functions and Implicit Expression Block Return Optimization
Master Rust expression-oriented functions: implicit tail returns (omitting semicolon), explicit return keyword, and block optimization schemas.
Rust Online Compiler
Open in Compilra IDE
Run and test Rust on Compilra
Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.