Errors
Unrecovable errors
These errors are called panics in rust, and they cause the program to quit. They can be caused by something like an out of index error, or explicitly with the panic!
macro.
rust
fn main() {
panic!("crash and burn");
}
Results: Recoverable Errors
A Result
is an enum that allows for handling when a function does not occur as expected.
rust
enum Result<T, E> {
Ok(T),
Err(E),
}
let greeting_file_result = File::open("hello.txt"); // Returns a result
let greeting_file = match greeting_file_result {
Ok(file) => file,
Err(error) => match error.kind() {
ErrorKind::NotFound => match File::create("hello.txt") {
Ok(fc) => fc,
Err(e) => panic!("Problem creating the file: {:?}", e),
},
other_error => {
panic!("Problem opening the file: {:?}", other_error);
}
},
};
Shortcuts for panicing on error
unwrap
can be used to throw an error automatically, or panic with an error message with expect
.
rust
let greeting_file = File::open("hello.txt").unwrap();
let greeting_file = File::open("hello.txt").expect("hello.txt should be included in this project");
You can also use unwrap_or_else
and pass a closure to return a value if something goes wrong.
rust
let greeting_file = File::open("hello.txt").unwrap_or_else(|| None ) // return something else
Propagate an error
If an error is returned to a function that also returns a Result
with a comparable error type, then you can use the ?
to return an error and propagate the error to the caller.
rust
fn read_username_from_file() -> Result<String, io::Error> {
let mut username_file = File::open("hello.txt")?;
let mut username = String::new();
username_file.read_to_string(&mut username)?;
Ok(username)
}
The same syntax can be used with Options as well.
rust
fn last_char_of_first_line(text: &str) -> Option<char> {
text.lines().next()?.chars().last()
}