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