Error Handling
Ways to handle errors in Rust:
- panic:
panic!() - Option:
Option<T>, variants:Some(T),None - Result:
Result<T, E>, variants:Ok(T),Err(E) - Error propagating:
?
fn read() -> Result<String, io::Error> {
let mut s = String::new();
File::open("hello.txt")?.read_to_string(&mut s)?;
Ok(s)
}
panic
When to panic
- In example code or tests.
- When you know
Errnever happens,let ip: IpAddr = "127.0.0.1".parse().unwrap()
panic!("This is totally wrong!");
panic can be conditionally compiled. Currenty available values are abort and unwind.
Option
Unwrap of Option and Result
unwrap and expect can return the contained Some/Ok value.
- it will panic if value is
None/Err
Defaults
orandor_elsecan be used to return default value when contained value not matched.unwrap_orget_or_insert
Combinators
andand_thenmapmap_or
Error Propagating with ?
fn do_the_thing(i: i32) -> Result<i32, Error> {
let i = match halves_if_even(i) {
Ok(i) => i,
Err(e) => return Err(e),
};
// use `i`
}
// can be written with
fn do_the_thing(i: i32) -> Result<i32, Error> {
let i = halves_if_even(i)?;
// use `i`
}
Result
The Result type can also be used in main function.