1Syntax::Keyword::Try(3)User Contributed Perl DocumentatioSnyntax::Keyword::Try(3)
2
3
4

NAME

6       "Syntax::Keyword::Try" - a "try/catch/finally" syntax for perl
7

SYNOPSIS

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

DESCRIPTION

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

Experimental Features

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

KEYWORDS

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
209       Note that the "finally" syntax is not available when using this module
210       via Feature::Compat::Try, as it is not expected that syntax will be
211       added to the core perl 'try' feature. This is because a more general-
212       purpose ability may be added instead, under the name 'defer'. If you
213       wish to write code that may more easily be forward-compatible with that
214       feature instead, you should consider using Syntax::Keyword::Defer
215       rather than using "finally" statements.
216

OTHER MODULES

218       There are already quite a number of modules on CPAN that provide a
219       "try/catch"-like syntax for Perl.
220
221       • Try
222
223       • TryCatch
224
225       • Try::Tiny
226
227       • Syntax::Feature::Try
228
229       In addition, core perl itself gained a "try/catch" syntax based on this
230       module at version 5.34.0. It is available as "use feature 'try'".
231
232       They are compared here, by feature:
233
234   True syntax plugin
235       Like Try and Syntax::Feature::Try, this module is implemented as a true
236       syntax plugin, allowing it to provide new parsing rules not available
237       to simple functions. Most notably here it means that the resulting
238       combination does not need to end in a semicolon.
239
240       The core "feature 'try'" is also implemented as true native syntax in
241       the perl parser.
242
243       In comparison, Try::Tiny is plain perl and provides its functionality
244       using regular perl functions; as such its syntax requires the trailing
245       semicolon.
246
247       TryCatch is a hybrid that uses Devel::Declare to parse the syntax tree.
248
249   @_ in a try or catch block
250       Because the "try" and "catch" block code is contained in a true block
251       rather than an entire anonymous subroutine, invoking it does not
252       interfere with the @_ arguments array. Code inside these blocks can
253       interact with the containing function's array as before.
254
255       This feature is unique among these modules; none of the others listed
256       have this ability.
257
258       The core "feature 'try'" also behaves in this manner.
259
260   "return" in a try or catch block
261       Like TryCatch and Syntax::Feature::Try, the "return" statement has its
262       usual effect within a subroutine containing syntax provided by this
263       module.  Namely, it causes the containing "sub" itself to return.
264
265       It also behaves this way using the core "feature 'try'".
266
267       In comparison, using Try or Try::Tiny mean that a "return" statement
268       will only exit from the "try" block.
269
270   "next"/"last"/"redo" in a try or catch block
271       The loop control keywords of "next", "last" and "redo" have their usual
272       effect on dynamically contained loops.
273
274       These also work fine when using the core "feature 'try'".
275
276       Syntax::Feature::Try documents that these do not work there. The other
277       modules make no statement either way.
278
279   Value Semantics
280       Like Try and Syntax::Feature::Try, the syntax provided by this module
281       only works as a syntax-level statement and not an expression. You
282       cannot assign from the result of a "try" block. A common workaround is
283       to wrap the "try/catch" statement inside a "do" block, where its final
284       expression can be captured and used as a value.
285
286       The same "do" block wrapping also works for the core "feature 'try'".
287
288       In comparison, the behaviour implemented by Try::Tiny can be used as a
289       valued expression, such as assigned to a variable or returned to the
290       caller of its containing function.
291
292   "try" without "catch"
293       Like Syntax::Feature::Try, the syntax provided by this module allows a
294       "try" block to be followed by only a "finally" block, with no "catch".
295       In this case, exceptions thrown by code contained by the "try" are not
296       suppressed, instead they propagate as normal to callers. This matches
297       the behaviour familiar to Java or C++ programmers.
298
299       In comparison, the code provided by Try and Try::Tiny always suppress
300       exception propagation even without an actual "catch" block.
301
302       The TryCatch module does not allow a "try" block not followed by
303       "catch".
304
305       The core "feature 'try'" does not implement "finally" at all, and also
306       requires that every "try" block be followed by a "catch".
307
308   Typed "catch"
309       Try and Try::Tiny make no attempt to perform any kind of typed dispatch
310       to distinguish kinds of exception caught by "catch" blocks.
311
312       Likewise the core "feature 'try'" currently does not provide this
313       ability, though it remains an area of ongoing design work.
314
315       TryCatch and Syntax::Feature::Try both attempt to provide a kind of
316       typed dispatch where different classes of exception are caught by
317       different blocks of code, or propagated up entirely to callers.
318
319       This module provides such an ability, via the currently-experimental
320       "catch (VAR cond...)" syntax.
321
322       The design thoughts continue on the RT ticket
323       <https://rt.cpan.org/Ticket/Display.html?id=123918>.
324

WITH OTHER MODULES

326   Future::AsyncAwait
327       As of "Future::AsyncAwait" version 0.10 and Syntax::Keyword::Try
328       version 0.07, cross-module integration tests assert that basic
329       "try/catch" blocks inside an "async sub" work correctly, including
330       those that attempt to "return" from inside "try".
331
332          use Future::AsyncAwait;
333          use Syntax::Keyword::Try;
334
335          async sub attempt
336          {
337             try {
338                await func();
339                return "success";
340             }
341             catch {
342                return "failed";
343             }
344          }
345

ISSUES

347   Thread-safety at load time cannot be assured before perl 5.16
348       On perl versions 5.16 and above this module is thread-safe.
349
350       On perl version 5.14 this module is thread-safe provided that it is
351       "use"d before any additional threads are created.
352
353       However, when using 5.14 there is a race condition if this module is
354       loaded late in the program startup, after additional threads have been
355       created. This leads to the potential for it to be started up multiple
356       times concurrently, which creates data races when modifying internal
357       structures and likely leads to a segmentation fault, either during load
358       or soon after when more code is compiled.
359
360       As a workaround, for any such program that creates multiple threads,
361       loads additional code (such as dynamically-discovered plugins), and has
362       to run on 5.14, it should make sure to
363
364          use Syntax::Keyword::Try;
365
366       early on in startup, before it spins out any additional threads.
367
368       (See also <https://rt.cpan.org/Public/Bug/Display.html?id=123547>)
369
370   $@ is not local'ised by "try do" before perl 5.24
371       On perl versions 5.24 and above, or when using only control-flow
372       statement syntax, $@ is always correctly "local"ised.
373
374       However, when using the experimental value-yielding expression version
375       "try do {...}" on perl versions 5.22 or older, the "local"isation of $@
376       does not correctly apply around the expression. After such an
377       expression, the value of $@ will leak out if a failure happened and the
378       "catch" block was invoked, overwriting any previous value that was
379       visible there.
380
381       (See also <https://rt.cpan.org/Public/Bug/Display.html?id=124366>)
382

ACKNOWLEDGEMENTS

384       With thanks to "Zefram", "ilmari" and others from "irc.perl.org/#p5p"
385       for assisting with trickier bits of XS logic.
386

AUTHOR

388       Paul Evans <leonerd@leonerd.org.uk>
389
390
391
392perl v5.34.0                      2021-10-14           Syntax::Keyword::Try(3)
Impressum