Re:Go’ing Insane: Endless Error Handling
by chrismorgan on Tuesday September 14, 2021 @09:07AM
(#28524163)
Rust’s Result-based error handling is fairly similar to checked exceptions—all errors must be handled, whether you do something with them, ignore them or propagate them to the caller—but without the pain of checked exceptions, because the errors are just a normal part of the type system, which makes them much easier to work with in various ways (some of which are seen in the various comments here): the return type Result<T, E> is either a T (labelled “Ok”), or an E (labelled “Err”).
The question mark operator just gives you an easy way of doing perhaps the most common handling of errors, which is propagating it up to the caller to worry about. So somewhere along the way you’re going to need to actually handle it (or explicitly ignore it), though it’s also possible in simple programs to let Rust handle it, by having your main function return a Result (that is, something like `fn main() -> Result<(), Error>`), in which case if it’s an Err it prints the error (roughly `eprintln!("Error: {:?}", err);`) and exits with status code 1.
The question mark operator just gives you an easy way of doing perhaps the most common handling of errors, which is propagating it up to the caller to worry about. So somewhere along the way you’re going to need to actually handle it (or explicitly ignore it), though it’s also possible in simple programs to let Rust handle it, by having your main function return a Result (that is, something like `fn main() -> Result<(), Error>`), in which case if it’s an Err it prints the error (roughly `eprintln!("Error: {:?}", err);`) and exits with status code 1.