1Syntax::Keyword::Try(3)User Contributed Perl DocumentatioSnyntax::Keyword::Try(3)
2
3
4
6 "Syntax::Keyword::Try" - a "try/catch/finally" syntax for perl
7
9 use Syntax::Keyword::Try;
10
11 sub foo {
12 try {
13 attempt_a_thing();
14 return "success";
15 }
16 catch ($e) {
17 warn "It failed - $e";
18 return "failure";
19 }
20 }
21
23 This module provides a syntax plugin that implements exception-handling
24 semantics in a form familiar to users of other languages, being built
25 on a block labeled with the "try" keyword, followed by at least one of
26 a "catch" or "finally" block.
27
28 As well as providing a handy syntax for this useful behaviour, this
29 module also serves to contain a number of code examples for how to
30 implement parser plugins and manipulate optrees to provide new syntax
31 and behaviours for perl code.
32
34 Some of the features of this module are currently marked as
35 experimental. They will provoke warnings in the "experimental"
36 category, unless silenced.
37
38 You can silence this with "no warnings 'experimental'" but then that
39 will silence every experimental warning, which may hide others
40 unintentionally. For a more fine-grained approach you can instead use
41 the import line for this module to only silence this module's warnings
42 selectively:
43
44 use Syntax::Keyword::Try qw( try :experimental(typed) );
45
46 use Syntax::Keyword::Try qw( try :experimental ); # all of the above
47
48 Don't forget to import the main "try" symbol itself, to activate the
49 syntax.
50
52 try
53 try {
54 STATEMENTS...
55 }
56 ...
57
58 A "try" statement provides the main body of code that will be invoked,
59 and must be followed by either a "catch" statement, a "finally"
60 statement, or both.
61
62 Execution of the "try" statement itself begins from the block given to
63 the statement and continues until either it throws an exception, or
64 completes successfully by reaching the end of the block. What will
65 happen next depends on the presence of a "catch" or "finally" statement
66 immediately following it.
67
68 The body of a "try {}" block may contain a "return" expression. If
69 executed, such an expression will cause the entire containing function
70 to return with the value provided. This is different from a plain "eval
71 {}" block, in which circumstance only the "eval" itself would return,
72 not the entire function.
73
74 The body of a "try {}" block may contain loop control expressions
75 ("redo", "next", "last") which will have their usual effect on any
76 loops that the "try {}" block is contained by.
77
78 The parsing rules for the set of statements (the "try" block and its
79 associated "catch" and "finally") are such that they are parsed as a
80 self- contained statement. Because of this, there is no need to end
81 with a terminating semicolon.
82
83 Note (especially to users of Try::Tiny and similar) that the "try {}"
84 block itself does not necessarily stop exceptions thrown inside it from
85 propagating outside. It is the presence of a later "catch {}" block
86 which causes this to happen. A "try" with only a "finally" and no
87 "catch" will still propagate exceptions up to callers as normal.
88
89 catch
90 ...
91 catch ($var) {
92 STATEMENTS...
93 }
94
95 or
96
97 ...
98 catch {
99 STATEMENTS...
100 }
101
102 A "catch" statement provides a block of code to the preceding "try"
103 statement that will be invoked in the case that the main block of code
104 throws an exception. Optionally a new lexical variable can be provided
105 to store the exception in. If not provided, the "catch" block can
106 inspect the raised exception by looking in $@ instead.
107
108 Presence of this "catch" statement causes any exception thrown by the
109 preceding "try" block to be non-fatal to the surrounding code. If the
110 "catch" block wishes to optionally handle some exceptions but not
111 others, it can re-raise it (or another exception) by calling "die" in
112 the usual manner.
113
114 As with "try", the body of a "catch {}" block may also contain a
115 "return" expression, which as before, has its usual meaning, causing
116 the entire containing function to return with the given value. The body
117 may also contain loop control expressions ("redo", "next" or "last")
118 which also have their usual effect.
119
120 If a "catch" statement is not given, then any exceptions raised by the
121 "try" block are raised to the caller in the usual way.
122
123 catch (Typed)
124 ...
125 catch ($var isa Class) { ... }
126
127 ...
128 catch ($var =~ m/^Regexp match/) { ... }
129
130 Experimental; since version 0.15.
131
132 Optionally, multiple catch statements can be provided, where each block
133 is given a guarding condition, to control whether or not it will catch
134 particular exception values. Use of this syntax will provoke an
135 "experimental" category warning on supporting perl versions, unless
136 silenced by importing the ":experimental(typed)" tag (see above).
137
138 Two kinds of condition are supported:
139
140 ·
141
142
143 catch ($var isa Class)
144
145 The block is invoked only if the caught exception is a blessed
146 object, and derives from the given package name.
147
148 On Perl version 5.32 onwards, this condition test is implemented
149 using the same op type that the core "$var isa Class" syntax is
150 provided by and works in exactly the same way.
151
152 On older perl versions it is emulated by a compatibility function.
153 Currently this function does not respect a "->isa" method overload
154 on the exception instance. Usually this should not be a problem, as
155 exception class types rarely provide such a method.
156
157 ·
158
159
160 catch ($var =~ m/regexp/)
161
162 The block is invoked only if the caught exception is a string that
163 matches the given regexp.
164
165 When an exception is caught, each condition is tested in the order they
166 are written in, until a matching case is found. If such a case is found
167 the corresponding block is invoked, and no further condition is tested.
168 If no contional block matched and there is a default (unconditional)
169 block at the end then that is invoked instead. If no such block exists,
170 then the exception is propagated up to the calling scope.
171
172 finally
173 ...
174 finally {
175 STATEMENTS...
176 }
177
178 A "finally" statement provides a block of code to the preceding "try"
179 statement (or "try/catch" pair) which is executed afterwards, both in
180 the case of a normal execution or a thrown exception. This code block
181 may be used to provide whatever clean-up operations might be required
182 by preceding code.
183
184 Because it is executed during a stack cleanup operation, a "finally {}"
185 block may not cause the containing function to return, or to alter the
186 return value of it. It also cannot see the containing function's @_
187 arguments array (though as it is block scoped within the function, it
188 will continue to share any normal lexical variables declared up until
189 that point). It is protected from disturbing the value of $@. If the
190 "finally {}" block code throws an exception, this will be printed as a
191 warning and discarded, leaving $@ containing the original exception, if
192 one existed.
193
195 Warning: the feature described in this section is experimental.
196 This experiment may be stablised in a later version, or may be
197 altered or removed without further notice. It is present here for
198 testing and evaluation purposes.
199
200 Additionally, on perl versions 5.18 and later, it will produce a
201 warning in the "experimental" category.
202
203 The syntax provided by this module may be used as a value-yielding
204 expression. Because this syntax is new, experimental, and somewhat
205 surprising, it must be specifically requested by name "try_value":
206
207 use Syntax::Keyword::Try qw( try try_value );
208
209 my $result = try do { ... } catch { ... };
210
211 Also, on Perl versions 5.24 and later:
212
213 my $result = try do { ... } finally { ... };
214
215 my $result = try do { ... } catch { ... } finally { ... };
216
217 Specifically, note that the expression must be spelled as "try do { ...
218 }" so that the syntax is distinct from that used by control-flow
219 statements. The interposed "do" keyword reminds the reader, and
220 instructs the syntax parser, that this will be an expression, not a
221 statement. It is not necessary to similarly notate the "catch" or
222 "finally" blocks.
223
224 In this case, the syntax behaves syntactically like an expression, and
225 may appear anywhere a normal expression is allowed. It follows similar
226 semantics to the purely control-flow case; if the code in the "try"
227 block does not throw an exception, then the expression as a whole
228 yields whatever value the "try" expression did. If it fails, then the
229 "catch" block is executed and the expression yields its resulting value
230 instead. A "finally" block, if present, will be evaluated for side-
231 effects before the rest of the expression returns.
232
233 Remember that, as in the control-flow case, the "return" keyword will
234 cause the entire containing function to return, not just the "try"
235 block.
236
238 There are already quite a number of modules on CPAN that provide a
239 "try/catch"-like syntax for Perl.
240
241 · Try
242
243 · TryCatch
244
245 · Try::Tiny
246
247 · Syntax::Feature::Try
248
249 They are compared here, by feature:
250
251 True syntax plugin
252 Like Try and Syntax::Feature::Try, this module is implemented as a true
253 syntax plugin, allowing it to provide new parsing rules not available
254 to simple functions. Most notably here it means that the resulting
255 combination does not need to end in a semicolon.
256
257 In comparison, Try::Tiny is plain perl and provides its functionality
258 using regular perl functions; as such its syntax requires the trailing
259 semicolon.
260
261 TryCatch is a hybrid that uses Devel::Declare to parse the syntax tree.
262
263 @_ in a try or catch block
264 Because the "try" and "catch" block code is contained in a true block
265 rather than an entire anonymous subroutine, invoking it does not
266 interfere with the @_ arguments array. Code inside these blocks can
267 interact with the containing function's array as before.
268
269 This feature is unique among these modules; none of the others listed
270 have this ability.
271
272 "return" in a try or catch block
273 Like TryCatch and Syntax::Feature::Try, the "return" statement has its
274 usual effect within a subroutine containing syntax provided by this
275 module. Namely, it causes the containing "sub" itself to return.
276
277 In comparison, using Try or Try::Tiny mean that a "return" statement
278 will only exit from the "try" block.
279
280 "next"/"last"/"redo" in a try or catch block
281 The loop control keywords of "next", "last" and "redo" have their usual
282 effect on dynamically contained loops.
283
284 Syntax::Feature::Try documents that these do not work there. The other
285 modules make no statement either way.
286
287 Value Semantics
288 Like Try and Syntax::Feature::Try, the syntax provided by this module
289 only works as a syntax-level statement and not an expression when the
290 experimental "try_value" feature described above has not been enabled.
291 You cannot assign from the result of a "try" block. Additionally,
292 final-expression value semantics do not work, so it cannot be contained
293 by a "do" block to yield this value.
294
295 In comparison, the behaviour implemented by Try::Tiny can be used as a
296 valued expression, such as assigned to a variable or returned to the
297 caller of its containing function. Such ability is provided by this
298 module if the experimental "try_value" feature is enabled, though it
299 must be spelled differently as "try do { ... }".
300
301 "try" without "catch"
302 Like Syntax::Feature::Try, the syntax provided by this module allows a
303 "try" block to be followed by only a "finally" block, with no "catch".
304 In this case, exceptions thrown by code contained by the "try" are not
305 suppressed, instead they propagate as normal to callers. This matches
306 the behaviour familiar to Java or C++ programmers.
307
308 In comparison, the code provided by Try and Try::Tiny always suppress
309 exception propagation even without an actual "catch" block.
310
311 The TryCatch module does not allow a "try" block not followed by
312 "catch".
313
314 Typed "catch"
315 Try and Try::Tiny make no attempt to perform any kind of typed dispatch
316 to distinguish kinds of exception caught by "catch" blocks.
317
318 TryCatch and Syntax::Feature::Try both attempt to provide a kind of
319 typed dispatch where different classes of exception are caught by
320 different blocks of code, or propagated up entirely to callers.
321
322 This module provides such an ability, via the currently-experimental
323 "catch (VAR cond...)" syntax.
324
325 The design thoughts continue on the RT ticket
326 <https://rt.cpan.org/Ticket/Display.html?id=123918>.
327
329 Future::AsyncAwait
330 As of "Future::AsyncAwait" version 0.10 and Syntax::Keyword::Try
331 version 0.07, cross-module integration tests assert that basic
332 "try/catch" blocks inside an "async sub" work correctly, including
333 those that attempt to "return" from inside "try".
334
335 use Future::AsyncAwait;
336 use Syntax::Keyword::Try;
337
338 async sub attempt
339 {
340 try {
341 await func();
342 return "success";
343 }
344 catch {
345 return "failed";
346 }
347 }
348
350 Thread-safety at load time cannot be assured before perl 5.16
351 On perl versions 5.16 and above this module is thread-safe.
352
353 On perl version 5.14 this module is thread-safe provided that it is
354 "use"d before any additional threads are created.
355
356 However, when using 5.14 there is a race condition if this module is
357 loaded late in the program startup, after additional threads have been
358 created. This leads to the potential for it to be started up multiple
359 times concurrently, which creates data races when modifying internal
360 structures and likely leads to a segmentation fault, either during load
361 or soon after when more code is compiled.
362
363 As a workaround, for any such program that creates multiple threads,
364 loads additional code (such as dynamically-discovered plugins), and has
365 to run on 5.14, it should make sure to
366
367 use Syntax::Keyword::Try;
368
369 early on in startup, before it spins out any additional threads.
370
371 (See also <https://rt.cpan.org/Public/Bug/Display.html?id=123547>)
372
373 $@ is not local'ised by "try do" before perl 5.24
374 On perl versions 5.24 and above, or when using only control-flow
375 statement syntax, $@ is always correctly "local"ised.
376
377 However, when using the experimental value-yielding expression version
378 "try do {...}" on perl versions 5.22 or older, the "local"isation of $@
379 does not correctly apply around the expression. After such an
380 expression, the value of $@ will leak out if a failure happened and the
381 "catch" block was invoked, overwriting any previous value that was
382 visible there.
383
384 (See also <https://rt.cpan.org/Public/Bug/Display.html?id=124366>)
385
387 With thanks to "Zefram", "ilmari" and others from "irc.perl.org/#p5p"
388 for assisting with trickier bits of XS logic.
389
391 Paul Evans <leonerd@leonerd.org.uk>
392
393
394
395perl v5.32.0 2020-08-03 Syntax::Keyword::Try(3)