@@ -80,14 +80,18 @@ which is what C<$*ERR.say> does, getting displayed on whatever constitutes the
80
80
standard error device in that moment, which will probably be the console by
81
81
default.
82
82
83
- A C<CATCH> block uses smartmatching similar to how C<given/when>
84
- smartmatches on options, thus it's possible to catch and handle various
85
- categories of exceptions inside a C<when> block. And it does so because,
86
- within the block, C<$_> is set to the exception that has been raised.
87
-
88
- To handle all exceptions, use a C<default> statement. This example prints out
89
- almost the same information as the normal backtrace printer; the I<dot>
90
- methods apply to C<$_>, which holds the L<C<Exception>|/type/Exception> within the C<CATCH> block.
83
+ Note that the match target is a role. To allow user defined exceptions
84
+ to match in the same manner, they must implement the given role. Just
85
+ existing in the same namespace will make them look alike but won't match
86
+ in a C<CATCH> block.
87
+
88
+ A C<CATCH> block places any exception thrown in its topic variable
89
+ (C<$_>), thus it's possible to catch and handle various categories of
90
+ exceptions inside a C<when> block. To handle all exceptions, use a
91
+ C<default> statement. This example prints out almost the same
92
+ information as the normal backtrace printer. Note that the I<dot>
93
+ methods apply to C<$_>, which holds the
94
+ L<C<Exception>|/type/Exception> within the C<CATCH> block.
91
95
92
96
CATCH {
93
97
default {
@@ -100,11 +104,20 @@ methods apply to C<$_>, which holds the L<C<Exception>|/type/Exception> within t
100
104
}
101
105
}
102
106
103
- Note that the match target is a role. To allow user defined exceptions to
104
- match in the same manner, they must implement the given role. Just existing
105
- in the same namespace will look alike but won't match in a C<CATCH> block.
107
+ While this is a very common pattern, it is not strictly necessary to use
108
+ C<default> or C<when> in a C<CATCH> block. This is done to prevent the
109
+ control flow from reaching the end of the block where, unless the
110
+ exception has been L<resumed|#Resuming_of_exceptions>, the exception
111
+ will continue to be thrown. Allowing this can be used for logging
112
+ purposes, for instance:
113
+
114
+ =for code
115
+ # In the outermost block of a script...
116
+ my IO::Handle:D $log = open sprintf('logs/%d-%d.txt', $*INIT-INSTANT, $*PID), :a;
117
+ CATCH { $log.printf: "[%d] Died with %s: %s$?NL", now, .^name, .message }
118
+ END { $log.close }
106
119
107
- Note that the C<CATCH> block semantics apply to the B<entire> lexical scope
120
+ The C<CATCH> block semantics apply to the B<entire> lexical scope
108
121
in which it is defined, B<regardless> of where it is defined inside that
109
122
lexical scope. It is therefore advised to put any C<CATCH> block at the
110
123
start of the lexical scope to which they apply so that the casual reader
0 commit comments