In Rust, You Cannot Ignore an Error. The Compiler Guarantees It.
Not a Medium member? Read it here
Mistakes are inevitable in life not just programming, but every language has some sort of errors handling paradigm for it. Whether it’s a missing file, invalid user input, or a failed network request, errors happen. But the way a language handles errors determines whether your program crashes unexpectedly or gracefully recovers. Poor error handling can also introduce security vulnerabilities, such as allowing hackers to access out-of-bounds data, which should never be the case and must be prevented or blocked.
This section covers error handling in Rust. Unlike many other languages, Rust does not use the concept of exceptions. Instead, it has categorized errors as recoverable and non-recoverable. Recoverable errors are handled using the Result type, while non-recoverable errors are handled using the panic! macro. Additionally, Rust provides the ? operator for propagating errors in a concise and ergonomic way.
Why is it Different from Exceptions?
- Compile-time safety: Rust forces you to acknowledge and handle errors, preventing many runtime crashes.
- No hidden control flow: Unlike exceptions, Rust’s errors are explicit, meaning you always know when a function might fail.
- Performance : Rust avoids the overhead of exception handling by using Result and Option, which are just enums under the hood.
Wait a second — we will cover these two categories, but also touch on Rust’s unique approach to ensuring safety and reliability at compile time. Such as:
- The Two Error Categories
- The Role of Ownership and Borrowing in Error Prevention
- Custom Error Types
- Error Propagation Patterns
- Panic Handling and Recovery
- Testing and Debugging Errors
- Real-World Examples
- Practical Exercise
1.1 The Two Error Categories
Rust categorizes errors into two distinct groups, each requiring different handling approaches:
Unrecoverable Errors (panic!)
Sometimes, a program encounters an issue where it cannot run safely anymore , meansing it has encountered a critical issue where continuing makes no sense. Such as:
- Trying to access an index in an array that doesn’t exist.
- Dividing a number by zero.
In such cases, Rust allows the program to crash intentionally using the panic! macro. This is called “panicking” in Rust. When a program panics, it stops execution, prints an error message, and cleans up resources by “unwinding” the stack (unless configured otherwise).
fn main() {
let v = vec![1, 2, 3];
println!("{}", v[99]); // This will panic: index out of bounds
}
fn main() {
let v = vec![1, 2, 3];
println!("{}", v[99]); // This will panic: index out of bounds
}
- Immediate Program Termination: The program stops running when it panics.
- Stack Unwinding vs. Abort: By default, Rust “unwinds” the stack (cleans up resources), but you can configure it to “abort” immediately in your
Cargo.tomlfile.
When to Use panic!:
- During development for debugging (e.g., catching unexpected issues).
- For critical failures like invalid preconditions or unrecoverable system states (e.g., memory corruption).
i32 {
if y == 0 {
panic!("Division by zero is not allowed!");
}
x / y
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
fn divide(x: i32, y: i32) -> i32 {
if y == 0 {
panic!("Division by zero is not allowed!");
}
x / y
}
fn divide(x: i32, y: i32) -> i32 {
if y == 0 {
panic!("Division by zero is not allowed!");
}
x / y
}
Here , in the example panic!() stops execution, prints an error message, and unwinds the stack. While useful in debugging, it’s discouraged in production code.
Recoverable Errors (Result<T, E>)
Some errors can be anticipated and handled properly. Examples:
- A file might not exist when trying to read it.
- A network request might fail due to connectivity issues.
For such cases, Rust provides the Result<T, E> enum:
<button data-code="enum Result {
Ok(T),
Err(E),
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
enum Result<T, E> {
Ok(T),
Err(E),
}
enum Result<T, E> {
Ok(T),
Err(E),
}
Why Use Result?
- It forces developers to explicitly handle errors instead of ignoring them.
- It makes the code safer and more predictable.
- Have a look at this example:
Result {
let f = File::open("config.toml")?;
Ok(f)
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
use std::fs::File;
fn read_config() -> Result<File, std::io::Error> {
let f = File::open("config.toml")?;
Ok(f)
}
use std::fs::File;
fn read_config() -> Result<File, std::io::Error> {
let f = File::open("config.toml")?;
Ok(f)
}
Lets crack it, Why Result:
Ok(T): Represents a successful operation with a value of typeT.Err(E): Represents an error with diagnostic information of typeE.- Mandatory Error Handling: You must handle
Resultusing pattern matching (e.g.,matchorif let). - The ? Operator: A shorthand for propagating errors. If an error occurs, it automatically returns the error from the function.
2. Preventing Errors with Ownership and Borrowing
Rust’s ownership system prevents memory errors at compile time:
- No Null Pointers:
Option<T>enforces handling of absent values. - No Data Races: The borrow checker ensures either one mutable reference or multiple immutable references.
- Memory Safety: Ownership rules prevent dangling pointers and double-frees.
Example: Avoiding Iterator Invalidation:
fn main() {
let mut vec = vec![1, 2, 3];
let first = &vec[0]; // Immutable borrow
vec.push(4); // Error: Cannot mutate while borrowed
}
fn main() {
let mut vec = vec![1, 2, 3];
let first = &vec[0]; // Immutable borrow
vec.push(4); // Error: Cannot mutate while borrowed
}
The borrow checker blocks this code, preventing undefined behavior.
3. Custom Error Types
For complex applications, define domain-specific errors.
Manual Implementation:
fmt::Result {
match self {
AppError::FileRead(e) => write!(f, "File error: {}", e),
AppError::InvalidFormat(s) => write!(f, "Invalid format: {}", s),
}
}
}
impl std::error::Error for AppError {}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
use std::fmt;
#[derive(Debug)]
enum AppError {
FileRead(std::io::Error),
InvalidFormat(String),
}
impl fmt::Display for AppError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
AppError::FileRead(e) => write!(f, "File error: {}", e),
AppError::InvalidFormat(s) => write!(f, "Invalid format: {}", s),
}
}
}
impl std::error::Error for AppError {}
use std::fmt;
#[derive(Debug)]
enum AppError {
FileRead(std::io::Error),
InvalidFormat(String),
}
impl fmt::Display for AppError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
AppError::FileRead(e) => write!(f, "File error: {}", e),
AppError::InvalidFormat(s) => write!(f, "Invalid format: {}", s),
}
}
}
impl std::error::Error for AppError {}
Using thiserror (Recommended):
use thiserror::Error;
#[derive(Error, Debug)]
enum AppError {
#[error("File error: {0}")]
FileRead(#[from] std::io::Error),
#[error("Invalid format: {0}")]
InvalidFormat(String),
}
use thiserror::Error;
#[derive(Error, Debug)]
enum AppError {
#[error("File error: {0}")]
FileRead(#[from] std::io::Error),
#[error("Invalid format: {0}")]
InvalidFormat(String),
}
thiserror auto-generates Display and Error implementations.
4. Error Propagation Patterns
Use the ? operator to streamline error handling.
Example: Chaining Errors:
Result {
let content = read_to_string("config.toml")?; // Converts io::Error to AppError via From
// … process content
Ok(())
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
use std::fs::read_to_string;
fn parse_config() -> Result<(), AppError> {
let content = read_to_string("config.toml")?; // Converts io::Error to AppError via From
// ... process content
Ok(())
}
use std::fs::read_to_string;
fn parse_config() -> Result<(), AppError> {
let content = read_to_string("config.toml")?; // Converts io::Error to AppError via From
// ... process content
Ok(())
}
Key Tips:
- Implement
Fromto convert between error types. - Use
map_errto adapt error contexts:
let content = File::open("config.toml") .map_err(|e| AppError::FileRead(e))?;
let content = File::open("config.toml") .map_err(|e| AppError::FileRead(e))?;
5. Panic Handling and Recovery
While panics are unrecoverable, you can isolate them in threads.
Example: Catching Panics:
Threads will be covered in next section
use std::panic;
fn main() {
let result = panic::catch_unwind(|| {
panic!("Oops!");
});
println!("Panic caught: {:?}", result.is_err());
}
use std::panic;
fn main() {
let result = panic::catch_unwind(|| {
panic!("Oops!");
});
println!("Panic caught: {:?}", result.is_err());
}
Use Cases:
- Preventing crashes in multi-threaded apps.
- Safeguarding against third-party code panics.
6. Testing and Debugging Errors
Testing Panics:
#[test]
#[should_panic(expected = "divide by zero")]
fn test_divide() {
divide(10, 0);
}
#[test]
#[should_panic(expected = "divide by zero")]
fn test_divide() {
divide(10, 0);
}
Testing Result:
#[test]
fn test_read_config() {
assert!(read_config().is_err());
}
#[test]
fn test_read_config() {
assert!(read_config().is_err());
}
Debugging:
- Set
RUST_BACKTRACE=1for detailed panic logs. - Use
dbg!()to inspect values:
let x = Some(10); dbg!(&x); // Prints file, line, and value
let x = Some(10); dbg!(&x); // Prints file, line, and value
7. Real-World Examples
Case Study: serde Deserialization:
The serde crate uses custom errors to report parsing failures, providing context like line numbers.
Community Wisdom:
- Libraries: Use
thiserrorfor precise, actionable errors. - Applications: Use
anyhowfor ergonomic error handling with context chains.
Production Code:
Result {
let config = read_config()
.context("Failed to read config")?; // Adds context to errors
Ok(())
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
use anyhow::{Context, Result};
fn main() -> Result<()> {
let config = read_config()
.context("Failed to read config")?; // Adds context to errors
Ok(())
}
use anyhow::{Context, Result};
fn main() -> Result<()> {
let config = read_config()
.context("Failed to read config")?; // Adds context to errors
Ok(())
}
8. Exercise: A Practical Application
To illustrate error handling in a real-world scenario, consider a simple application that manages a list of vehicles (cars). We define a Vehicle struct and a custom error type to handle cases where a vehicle isn’t found.
fmt::Result {
match self {
VehicleError::NotFound(id) =>
write!(f, "Vehicle with id {} not found", id),
}
}
}
impl std::error::Error for VehicleError {}
// Function to find a vehicle by its id.
fn find_vehicle(vehicles: &[Vehicle], id: u32) -> Result {
vehicles.iter().find(|v| v.id == id).ok_or(VehicleError::NotFound(id))
}
fn main() {
let vehicles = vec![
Vehicle { id: 1, model: String::from("Sedan LX") },
Vehicle { id: 2, model: String::from("Coupe GT") },
];
// Attempt to find a vehicle that does not exist.
match find_vehicle(&vehicles, 3) {
Ok(vehicle) => println!("Found vehicle: {:?}", vehicle),
Err(e) => println!("Error: {}", e),
}
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
use std::fmt;
// Define a simple Vehicle struct.
#[derive(Debug)]
struct Vehicle {
id: u32,
model: String,
}
// Custom error for vehicle operations.
#[derive(Debug)]
enum VehicleError {
NotFound(u32),
}
impl fmt::Display for VehicleError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
VehicleError::NotFound(id) =>
write!(f, "Vehicle with id {} not found", id),
}
}
}
impl std::error::Error for VehicleError {}
// Function to find a vehicle by its id.
fn find_vehicle(vehicles: &[Vehicle], id: u32) -> Result<&Vehicle, VehicleError> {
vehicles.iter().find(|v| v.id == id).ok_or(VehicleError::NotFound(id))
}
fn main() {
let vehicles = vec![
Vehicle { id: 1, model: String::from("Sedan LX") },
Vehicle { id: 2, model: String::from("Coupe GT") },
];
// Attempt to find a vehicle that does not exist.
match find_vehicle(&vehicles, 3) {
Ok(vehicle) => println!("Found vehicle: {:?}", vehicle),
Err(e) => println!("Error: {}", e),
}
}
use std::fmt;
// Define a simple Vehicle struct.
#[derive(Debug)]
struct Vehicle {
id: u32,
model: String,
}
// Custom error for vehicle operations.
#[derive(Debug)]
enum VehicleError {
NotFound(u32),
}
impl fmt::Display for VehicleError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
VehicleError::NotFound(id) =>
write!(f, "Vehicle with id {} not found", id),
}
}
}
impl std::error::Error for VehicleError {}
// Function to find a vehicle by its id.
fn find_vehicle(vehicles: &[Vehicle], id: u32) -> Result<&Vehicle, VehicleError> {
vehicles.iter().find(|v| v.id == id).ok_or(VehicleError::NotFound(id))
}
fn main() {
let vehicles = vec![
Vehicle { id: 1, model: String::from("Sedan LX") },
Vehicle { id: 2, model: String::from("Coupe GT") },
];
// Attempt to find a vehicle that does not exist.
match find_vehicle(&vehicles, 3) {
Ok(vehicle) => println!("Found vehicle: {:?}", vehicle),
Err(e) => println!("Error: {}", e),
}
}
Explanation:
- We define a
Vehiclestruct with anidandmodel. - The custom
VehicleErrorenum provides a clear error message when a vehicle isn’t found. - The
find_vehiclefunction searches a slice of vehicles for the matchingidand returns aResultthat uses the custom error type. - In
main, we demonstrate error handling by attempting to look up a vehicle with an id that does not exist, then pattern matching on the result to either display the vehicle or print the error.
Conclusion
Rust’s error handling is a blend of rigor and pragmatism. By distinguishing recoverable and unrecoverable errors, enforcing checks at compile time, and offering tools like Result, ?, and custom errors, Rust ensures your programs are both robust and efficient. Embrace these patterns to write code that not only handles failures gracefully but also prevents them upfront
In upcoming articles, we will discuss deeper concepts in Rust’s advanced type system features, including threads, concurrency but before that a real world application covering what we have learned so far is also in a pipeline.
Happy coding and safe assembling!
Follow this series and join us in mastering Rust from scratch!
Reach out here on Linkedin

