@@ -24,20 +24,30 @@ See also the macro [`compile_error!`], for raising errors during compilation.
24
24
25
25
# When to use `panic!` vs `Result`
26
26
27
- The Rust model of error handling groups errors into two major categories:
28
- recoverable and unrecoverable errors. For a recoverable error, such as a file
29
- not found error, it’s reasonable to report the problem to the user and retry
30
- the operation. Unrecoverable errors are always symptoms of bugs, like trying to
31
- access a location beyond the end of an array.
27
+ The Rust language provides two complementary systems for constructing /
28
+ representing, reporting, propagating, reacting to, and discarding errors. These
29
+ responsibilities are collectively known as "error handling." `panic!` and
30
+ `Result` are similar in that they are each the primary interface of their
31
+ respective error handling systems; however, the meaning these interfaces attach
32
+ to their errors and the responsibilities they fulfill within their respective
33
+ error handling systems differ.
32
34
33
- The Rust language and standard library provides `Result` and `panic!` as parts
34
- of two complementary systems for representing, reporting, propagating, reacting
35
- to, and discarding errors for in these two categories.
35
+ The `panic!` macro is used to construct errors that represent a bug that has
36
+ been detected in your program. With `panic!` you provide a message that
37
+ describes the bug and the language then constructs an error with that message,
38
+ reports it, and propagates it for you.
36
39
37
- The `panic!` macro is provided to represent unrecoverable errors, whereas the
38
- `Result` enum is provided to represent recoverable errors. For more detailed
39
- information about error handling check out the [book] or the [`std::result`]
40
- module docs.
40
+ `Result` on the other hand is used to wrap other types that represent either
41
+ the successful result of some computation, `Ok(T)`, or error types that
42
+ represent an anticipated runtime failure mode of that computation, `Err(E)`.
43
+ `Result` is used alongside user defined types which represent the various
44
+ anticipated runtime failure modes that the associated computation could
45
+ encounter. `Result` must be propagated manually, often with the the help of the
46
+ `?` operator and `Try` trait, and they must be reported manually, often with
47
+ the help of the `Error` trait.
48
+
49
+ For more detailed information about error handling check out the [book] or the
50
+ [`std::result`] module docs.
41
51
42
52
[ounwrap]: Option::unwrap
43
53
[runwrap]: Result::unwrap
0 commit comments