Nothing is Perfect and that includes the code that we programmers write everyday, seven days of the week and most of the year. This code we write will not always be perfect even if we check it thousand time. It will cause errors and tell us that something have gone wrong and we should fix it.
It is because of these errors that we are able to know whats wrong with our code. But these errors can also give information about our program to the ones with bad intentions. In order to void this from happening we do Error Handling in our code so that we can handles these errors beforehand and prevent the program from giving info to unwanted people or to prevent it from crashing.
Error Handling In Rust
Rust as any other language also provide ways to handle these errors in the code. It allows us to take actions before the code compiles.
Rust specifies errors in to two categories, recoverable and unrecoverable errors.
- Recoverable Errors are errors that the program does not crashes and restarts itself while also telling the user about the error.
- Unrecoverable Errors are errors that will casue the program to crash.
Recoverable Errors
Recoverable errors are errors that are not serious enough for the program to stop working and instead shows the error to the user and restarts the task. To handle Recoverbale errors in Rust we use Result
or Option
enum which looks something like this.
enum Result<T, E> {
Ok(T),
Err(E),
}
enum Option<T> {
Some(T),
None,
}
Suppose we want to open a file in our program but it could happen that the file we are trying to open does not exist. Rust instead of crashing the program will cause a recoverable error. This is beasue it may be that if the file doesn't exist we may also want to create it.
These two enums Result
and another one called Option
are used to recover these Errors. In the file example we use the Result enum to handle the error.
use std::fs::File;
fn main() {
let f = File::open("file.txt");
let f = match f {
Ok(file) => file,
Err(e) => panic!("{}", e),
}
}
UnRecoverable Errors
Unrevocerable errors are errors that will cause the program to crash and we cannot recover the state of the program. For example we have an array of 5 items and if we try to get item at index 6 it will cause an error called a panic
and will crash the program.
fn main() {
let a = vec![1,2,3,4,5];
a[6]; // Rust will panic! here
}
We can also crash the program ourselves if we want to or if something unexpected happens by using the panic!
macro.
fn main() {
let a: i32 = 1;
if a == -1 {
panic!("Exit out!");
} else {
println!("{}", a);
}
}
Before writing this article I though that the Error handeling in Rust would be simillar to what we do in Python but I was wrong. So this article is a little incomplete and may need some update in the future.