Rust groups errors into 2 categories, recoverable and unrecoverable
- recoverable errors rely on the
Result
type - unrecoverable errors use the panic macros
panic!
the panic macro terminates the current thread. One the things than can cause a panic to occur is trying to perform out-of-bounds access of an array
let vec = vec![1];
// trying to access non-existent index
vec[10];
Result is an enum that has 2 variables, Ok
and Err
.
enum Result<T, E>{
Ok(T),
Err(E)
}
this allows us to watch for potential panics in our code, and handle them differently. consider the following:
use std::fs::File;
let file: Result<File, Error> = File::open("somefile.txt");
let file: File = match file {
Ok(file: File) => file,
Err(error: Error) => panic!("a custom error description"),
_ => panic!("we can't tell what happened"),
}
if the Result
of the program is Ok
, the unwrap()
will return the value inside the Ok
for use, but if the Result
of the program is Err
, the unwrap()
wil call panic for us.
let file2 = File::open("error.txt").unwrap();
allows us to customize the error message. It allows to track the source of a panic much quicker.
let file3 = File::open("error.txt").expect("Error opening the file");