@@ -37,18 +37,45 @@ unexpected because they are bugs that should not happen. It would not make sense
37
37
to handle an error for QuickSort returning an incorrectly unsorted array, as
38
38
this should not happen.
39
39
40
- There are scenarios where using panic::catch_unwind is the correct choice, eg, a
40
+ ## Advantages
41
+
42
+ There are scenarios where using ` panic::catch_unwind ` is the correct choice, e.g. a
41
43
web server implementation wants to save an unwinding thread in order to send a
42
44
valid response if the route for that request (as in: logic outside of the web server
43
45
implementor's control) is producing a panic.
44
46
47
+ ## Disadvantages
48
+
49
+ ` panic::catch_unwind ` may not catch all panics in Rust. A panic in Rust is not always
50
+ implemented via unwinding, but can be implemented by aborting the process as well.
51
+ ` panic::catch_unwind ` only catches unwinding panics, not those that abort the process.
52
+
53
+ Also note that unwinding into Rust code with a foreign exception
54
+ (e.g. a an exception thrown from C++ code) is undefined behavior.
55
+
56
+ TODO: since Result::unwrap() converts the error to a string, it's harder to distinguish
57
+ between different kinds of errors than if we had matched the result directly.
58
+
59
+ ## Discussion
60
+
61
+ TODO:
62
+ ?-operator to propagate errors
63
+ explain why unwinding is bad
64
+ other disadvantages of panic::catch_unwind
65
+ + "The example could be improved by adding a function and which panics and catching the panic
66
+ in the caller, then matching the Result. Describing the example you could show how by returning
67
+ a Result, the Result-ness of the function is described in the signature."
68
+
45
69
Expected errors should not result in stack unwinding. Instead, expected errors
46
70
should be handled through the Result and Option types. [ The Rust Book's chapter
47
71
on Error Handling] ( https://doc.rust-lang.org/book/error-handling.html ) elaborates further on this.
48
72
49
73
## See also
50
74
51
75
[ The Rust Book: Error Handling] ( https://doc.rust-lang.org/book/error-handling.html )
76
+
52
77
[ Rust 1.9 announcement, which contains a description of this antipattern] ( http://blog.rust-lang.org/2016/05/26/Rust-1.9.html )
78
+
53
79
[ Result documentation] ( http://doc.rust-lang.org/std/result/enum.Result.html )
80
+
54
81
[ panic::catch_unwind documentation] ( https://doc.rust-lang.org/std/panic/fn.catch_unwind.html )
0 commit comments