Panics
https://doc.rust-lang.org/std/macro.panic.html
panic!() is also a macro. It violently stops execution with an error message, and
the file name / line number of the error, if enabled:
fn main() { panic!("Goodbye, cruel world"); } // output: thread 'main' panicked at 'Goodbye, cruel world', src/main.rs:3:5
Some methods also panic. For example, the Option type can contain something, or it can contain nothing. If .unwrap() is called on it, and it contains nothing, it panics:
fn main() { let o1: Option<i32> = Some(128); o1.unwrap(); // this is fine let o2: Option<i32> = None; o2.unwrap(); // this panics! } // output: thread 'main' panicked at 'called `Option::unwrap()` on a `None` value', src/libcore/option.rs:378:21
Functions that can fail typically return a Result:
fn main() { let s = std::str::from_utf8(&[240, 159, 141, 137]); println!("{:?}", s); // prints: Ok("π") let s = std::str::from_utf8(&[195, 40]); println!("{:?}", s); // prints: Err(Utf8Error { valid_up_to: 0, error_len: Some(1) }) }
If you want to panic in case of failure, you can .unwrap():
fn main() { let s = std::str::from_utf8(&[240, 159, 141, 137]).unwrap(); println!("{:?}", s); // prints: "π" let s = std::str::from_utf8(&[195, 40]).unwrap(); // prints: thread 'main' panicked at 'called `Result::unwrap()` // on an `Err` value: Utf8Error { valid_up_to: 0, error_len: Some(1) }', // src/libcore/result.rs:1165:5 }
Or .expect(), for a custom message:
fn main() { let s = std::str::from_utf8(&[195, 40]).expect("valid utf-8"); // prints: thread 'main' panicked at 'valid utf-8: Utf8Error // { valid_up_to: 0, error_len: Some(1) }', src/libcore/result.rs:1165:5 }
Or, you can match:
fn main() { match std::str::from_utf8(&[240, 159, 141, 137]) { Ok(s) => println!("{}", s), Err(e) => panic!(e), } // prints π }
Or you can if let:
fn main() { if let Ok(s) = std::str::from_utf8(&[240, 159, 141, 137]) { println!("{}", s); } // prints π }
Or you can bubble up the error:
fn main() -> Result<(), std::str::Utf8Error> { match std::str::from_utf8(&[240, 159, 141, 137]) { Ok(s) => println!("{}", s), Err(e) => return Err(e), } Ok(()) }
Or you can use ? to do it the concise way:
fn main() -> Result<(), std::str::Utf8Error> { let s = std::str::from_utf8(&[240, 159, 141, 137])?; println!("{}", s); Ok(()) }