Rust
December 2, 2026 6 min read

Error Handling in Rust

HS
HEMANT SINGH
Technical Writer & Educator

1. What Is Error Handling?

Error handling means detecting problems in a program and deciding what to do when they occur.

For example, consider a program that divides two numbers.

fn main() {
let a = 10;
let b = 0;

let result = a / b;

println!("Result: {}", result);
}

This program attempts to divide a number by zero. Integer division by zero causes a runtime panic.

Rust provides different ways to handle such situations safely.

The two major categories of errors in Rust are:

  1. Unrecoverable errors
  2. Recoverable errors

2. Unrecoverable Errors – panic!

An unrecoverable error is a problem from which the program cannot reasonably continue.

Rust provides the panic! macro to stop execution when such a problem occurs.

Syntax:

panic!("Error message");

Example:

fn main() {
println!("Program started");

panic!("Something went wrong!");

println!("Program finished");
}

Output:

Program started
thread 'main' panicked at ...
Something went wrong!

The last println! statement will not execute.

When should you use panic!?

Use panic! when:

  1. The program reaches an impossible state.
  2. Continuing execution would be unsafe.
  3. A programming error has occurred that should not be silently ignored.

Do not use panic! for ordinary user input errors that your program can handle.

3. Recoverable Errors

A recoverable error is a problem that your program can handle without stopping completely.

For example:

  1. A file is missing.
  2. A user enters an invalid number.
  3. A requested record is not found.

Rust commonly uses two types for handling these situations:

  1. Option<T>
  2. Result<T, E>

4. Understanding Option<T>

Sometimes a function may return a value, or it may have no value to return.

Rust uses Option<T> for this situation.

It has two variants:


Variant

Meaning

Some(value)

A value is available

None

No value is available

Example:

fn find_number() -> Option<i32> {
Some(100)
}

fn main() {
let result = find_number();

println!("{:?}", result);
}

Output:

Some(100)

Another example:

fn find_number() -> Option<i32> {
None
}

fn main() {
let result = find_number();

println!("{:?}", result);
}

Output:

None

Using match with Option

fn find_number() -> Option<i32> {
Some(100)
}

fn main() {
match find_number() {
Some(value) => println!("Found: {}", value),
None => println!("Number not found"),
}
}

Output:

Found: 100

Using if let with Option

If you only want to handle one variant, you can use if let.

fn main() {
let age: Option<i32> = Some(25);

if let Some(value) = age {
println!("Age: {}", value);
}
}

Output:

Age: 25

5. Understanding Result<T, E>

Result<T, E> is used when an operation can either succeed or fail.

It has two variants:


Variant

Meaning

Ok(value)

Operation successful

Err(error)

Operation failed

Here:

  1. T represents the success value type.
  2. E represents the error type.

Example:

fn divide(a: i32, b: i32) -> Result<i32, String> {
if b == 0 {
return Err("Cannot divide by zero".to_string());
}

Ok(a / b)
}

fn main() {
let result = divide(10, 2);

match result {
Ok(value) => println!("Result: {}", value),
Err(error) => println!("Error: {}", error),
}
}

Output:

Result: 5

Now try:

let result = divide(10, 0);

Output:

Error: Cannot divide by zero

The program does not panic because we handled the error using Result.

6. Understanding the ? Operator

The ? operator is used to propagate errors.

It makes error handling shorter and cleaner.

Consider this example:

use std::fs;

fn read_file() -> Result<String, std::io::Error> {
let content = fs::read_to_string("data.txt")?;

Ok(content)
}

fn main() {
match read_file() {
Ok(content) => println!("{}", content),
Err(error) => println!("Error: {}", error),
}
}

Explanation:

let content = fs::read_to_string("data.txt")?;

If the file is read successfully, the content is returned.

If reading fails, the error is returned immediately from read_file().

The ? operator does not automatically handle or print the error. It propagates the error to the calling function.

Important: The function using ? must return a compatible Result or Option type.

7. Understanding unwrap()

The unwrap() method extracts the value from Option or Result.

Example with Option:

fn main() {
let age = Some(25);

let value = age.unwrap();

println!("Age: {}", value);
}

Output:

Age: 25

Example with Result:

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

let value = result.unwrap();

println!("Value: {}", value);
}

Output:

Value: 100

What happens if unwrap fails?

fn main() {
let age: Option<i32> = None;

let value = age.unwrap();

println!("{}", value);
}

This causes a panic because there is no value inside None.

Important: Avoid using unwrap() when an error is reasonably possible in production code. Prefer match, if let, or ? where appropriate.

8. Understanding expect()

expect() works like unwrap(), but allows you to provide a custom panic message.

Example:

fn main() {
let age: Option<i32> = None;

let value = age.expect("Age value is missing");

println!("{}", value);
}

This causes a panic with the message:

Age value is missing

Difference between unwrap() and expect()


Method

Purpose

unwrap()

Extracts a value or panics

expect()

Extracts a value or panics with your message

9. Understanding unwrap_or()

Sometimes you want to use a default value if no value is available.

The unwrap_or() method helps with this.

Example:

fn main() {
let age: Option<i32> = None;

let value = age.unwrap_or(18);

println!("Age: {}", value);
}

Output:

Age: 18

Here, because age contains None, Rust uses the default value 18.

You can also use it with Result:

fn main() {
let result: Result<i32, &str> = Err("Failed");

let value = result.unwrap_or(0);

println!("Value: {}", value);
}

Output:

Value: 0

10. Converting Errors Using map_err()

The map_err() method allows you to transform an error into another error type.

Example:

fn main() {
let result: Result<i32, &str> = Err("Invalid input");

let new_result = result.map_err(|error| {
format!("Application Error: {}", error)
});

println!("{:?}", new_result);
}

Output:

Err("Application Error: Invalid input")

Here, the original error message is converted into a new String message.

11. Difference Between Option and Result


Feature

Option<T>

Result<T, E>

Purpose

Represents an optional value

Represents success or failure

Success variant

Some(value)

Ok(value)

Other variant

None

Err(error)

Error information

Does not contain an error message

Can contain error information

Common use

Value may be missing

Operation may fail

Example:

Use Option when searching for a student:

fn find_student() -> Option<String> {
Some("Hemant".to_string())
}

Use Result when saving student data:

fn save_student() -> Result<(), String> {
Ok(())
}

12. Common Mistakes


Mistake

Explanation

Using unwrap() everywhere

Can cause unexpected panics

Ignoring Result

Errors may remain unhandled

Confusing None and Err

None means no value; Err represents a failure

Using ? in an incompatible function

The function must return a compatible type

Using panic! for normal input errors

Prefer recoverable error handling