macro_rules! try { ($expr:expr $(,)?) => { ... };}👎Deprecated since 1.39.0: use the
? operator insteadExpand description
Unwraps a result or propagates its error.
The? operator was added to replacetry!and should be used instead. Furthermore,try is a reserved wordin Rust 2018, so if you must use it, you will need to use theraw-identifier syntax:r#try.
try! matches the givenResult. In case of theOk variant, theexpression has the value of the wrapped value.
In case of theErr variant, it retrieves the inner error.try! thenperforms conversion usingFrom. This provides automatic conversionbetween specialized errors and more general ones. The resultingerror is then immediately returned.
Because of the early return,try! can only be used in functions thatreturnResult.
§Examples
usestd::io;usestd::fs::File;usestd::io::prelude::*;enumMyError { FileWriteError}implFrom<io::Error>forMyError {fnfrom(e: io::Error) -> MyError { MyError::FileWriteError }}// The preferred method of quick returning Errorsfnwrite_to_file_question() ->Result<(), MyError> {letmutfile = File::create("my_best_friends.txt")?; file.write_all(b"This is a list of my best friends.")?;Ok(())}// The previous method of quick returning Errorsfnwrite_to_file_using_try() ->Result<(), MyError> {letmutfile =r#try!(File::create("my_best_friends.txt"));r#try!(file.write_all(b"This is a list of my best friends."));Ok(())}// This is equivalent to:fnwrite_to_file_using_match() ->Result<(), MyError> {letmutfile =r#try!(File::create("my_best_friends.txt"));matchfile.write_all(b"This is a list of my best friends.") {Ok(v) => v,Err(e) =>returnErr(From::from(e)), }Ok(())}