Rust errors
From wikinotes
Rust has two primary methods of handling errors.
panic!()
halts/exits the programResult
types are for handle-able errors
panic
- intended for halting application, not control flow
- have backtraces
panic!("tried to X but couldn't Y") // convert panic to result // (not intended for native rust code) let result = panic::catch_unwind(|| { panic!("oh no!"); });
Result
The result type is an enum, whose options
Ok, Err
have been merged into the global scope throughprelude
.Given this Result producing code:
struct MyError { value: isize } fn is_one(i: isize) -> Result<String, MyError> { if i == 1 { Ok("success".to_string()) } else { Err(MyError{value: i}) } }You can treat this like Option using
match
:let result = match is_one(2) { Ok(x) => format!("horay: {}", x), Err(_) => panic!("an error occurred") }; println!("{}", result);But there are more concise ways of handling this
// panic if error, otherwise return value let result = is_one(2) .unwrap() // panic with message if error, otherwise return value let result = is_one(2) .expect("an error occurred!") // <-- panic message