The Rust programming language provides two shortcut methods for handling errors: unwrap()
and expect()
. These methods are useful for cases where you are certain that the operation will succeed, and you want to avoid having to write a verbose match
expression.
unwrap()
The unwrap()
method returns the value inside the Ok
variant of a Result
enum, or panics with a default error message if the result is an Err
.
Here is an example:
use std::fs::File;
fn main() {
let greeting_file = File::open("hello.txt").unwrap();
}
If the hello.txt
file does not exist, this code will panic with the following error message:
thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: Os {
code: 2, kind: NotFound, message: "No such file or directory" }',
src/main.rs:4:49
expect()
The expect()
method is similar to unwrap()
, but it allows you to provide a custom error message if the operation fails.
Here is an example:
use std::fs::File;
fn main() {
let greeting_file = File::open("hello.txt")
.expect("hello.txt should be included in this project");
}
If the hello.txt
file does not exist, this code will panic with the following error message:
thread 'main' panicked at 'hello.txt should be included in this project: Os {
code: 2, kind: NotFound, message: "No such file or directory" }',
src/main.rs:5:10
Which method to use?
In general, it is best to avoid using unwrap()
and expect()
, unless you are certain that the operation will succeed. If it is possible for the operation to fail, you should use a match
expression to handle the error explicitly.
However, there are some cases where using unwrap()
or expect()
can be justified. For example, if you are reading a file from a predefined location, and you are certain that the file will always exist, then you can use unwrap()
to avoid writing a verbose match
expression.
Another case where using expect()
can be justified is if you are debugging your code. If you are trying to figure out why a particular operation is failing, you can use expect()
with a custom error message to get more information about the error.