5/5
# Error handling ## Example Execute the following command to run [`./solutions/examples/error.rs`](https://github.com/Cyfrin/rust-crash-course/blob/main/topics/error/solutions/examples/error.rs) ```shell cargo run --example error ``` ## Exercises Exercises are in [`./exercises/src/lib.rs`](https://github.com/Cyfrin/rust-crash-course/blob/main/topics/error/exercises/src/lib.rs) ### Exercise 1 ```rust pub fn div(x: u32, y: u32) -> Result<u32, MathError> { todo!(); } ``` Return `MathError` if `y` is 0. Otherwise return `x / y`. ### Exercise 2 ```rust pub fn get(v: &[u32], i: usize, default_val: u32) -> u32 { todo!(); } ``` Return `v[i]` if `i` is a valid index. Otherwise return `default_val`. ### Test ```shell cargo test ```
Execute the following command to run ./solutions/examples/error.rs
Exercises are in ./exercises/src/lib.rs
Return MathError
if y
is 0. Otherwise return x / y
.
Return v[i]
if i
is a valid index. Otherwise return default_val
.
A foundational introduction to Error handling - Learn to manage potential failures in Rust by implementing a division function using `Result` to handle division by zero. You'll also practice defensive programming by creating a slice access function that returns a default value for invalid indices.
Previous lesson
Previous
Next lesson
Next
Give us feedback
Course Overview
About the course
Introduction to the Rust programming language
Rust variables and functions
Scalar types, arrays, strings, enum, structs, vectors, and hash maps in Rust
Rust control flows: If / else, if let and let else, loop, match
Rust ownership, including borrow and references
Rust error handling
Rust Modules
Rust Traits
Last updated on September 3, 2025
Rust Developer
Rust Programming BasicsDuration: 6min
Duration: 18min
Duration: 47min
Duration: 15min
Duration: 19min
Duration: 8min
Duration: 12min
Duration: 46min
Duration: 14min
Course Overview
About the course
Introduction to the Rust programming language
Rust variables and functions
Scalar types, arrays, strings, enum, structs, vectors, and hash maps in Rust
Rust control flows: If / else, if let and let else, loop, match
Rust ownership, including borrow and references
Rust error handling
Rust Modules
Rust Traits
Last updated on September 3, 2025