101591 Views
79842 Views
45596 Views
44332 Views
40991 Views
33419 Views
Raspberry Pi Time machine
Now Ad-Free
Guiding Light
Sync Files on your Pis, with Syncthing
NextCloud
Buddy Jr.
Introduction to FreeCAD for Beginners
Building a Robot Arm with Raspberry Pi and PCA9685
Building User Authentication for Static Sites with FastAPI
Mastering Pydantic for Robust Data Validation
Mastering Markdown for Documentation with Jekyll
Introduction to Rust
KevsRobots Learning Platform
42% Percent Complete
By Kevin McAleer, 2 Minutes
Error handling is a critical part of programming. Rust handles errors through its type system, specifically with the Option and Result types, rather than exceptions. This lesson explains how these types work and how they are used in Rust for error handling and propagation.
Option
Result
The Option type is used in Rust when a value could be something or nothing (None). This type is used as a safer alternative to null references in other languages.
None
let some_number = Some(5); let no_number: Option<i32> = None;
The Result type is used when operations could fail. It returns Ok(value) if the operation is successful, or Err(e) if it fails. This approach makes you explicitly handle errors, leading to more robust code.
Ok(value)
Err(e)
fn divide(numerator: f64, denominator: f64) -> Result<f64, &'static str> { if denominator == 0.0 { Err("Cannot divide by zero") } else { Ok(numerator / denominator) } }
Instead of handling errors immediately, sometimes it’s more appropriate to propagate them to the calling code. Rust makes error propagation concise and safe with the ? operator.
?
fn get_divided_result(numerator: f64, denominator: f64) -> Result<f64, &'static str> { let result = divide(numerator, denominator)?; Ok(result) }
The ? operator automatically propagates the error if the operation fails, simplifying error handling especially when multiple operations could fail.
In this lesson, you’ve learned about Rust’s approach to error handling using the Option and Result types and explored how these can be used to handle and propagate errors in a safe, explicit manner. Understanding and utilizing these concepts are fundamental in writing robust Rust applications.
< Previous Next >