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 {
13 try {
14 attempt_a_thing();
15 return "success";
16 }
17 catch {
18 warn "It failed - $@";
19 return "failure";
20 }
21 }
22
24 This module provides a syntax plugin that implements exception-handling
25 semantics in a form familiar to users of other languages, being built
26 on a block labeled with the "try" keyword, followed by at least one of
27 a "catch" or "finally" block.
28
29 As well as providing a handy syntax for this useful behaviour, this
30 module also serves to contain a number of code examples for how to
31 implement parser plugins and manipulate optrees to provide new syntax
32 and behaviours for perl code.
33
35 try
36 try {
37 STATEMENTS...
38 }
39 ...
40
41 A "try" statement provides the main body of code that will be invoked,
42 and must be followed by either a "catch" statement, a "finally"
43 statement, or both.
44
45 Execution of the "try" statement itself begins from the block given to
46 the statement and continues until either it throws an exception, or
47 completes successfully by reaching the end of the block. What will
48 happen next depends on the presence of a "catch" or "finally" statement
49 immediately following it.
50
51 The body of a "try {}" block may contain a "return" expression. If
52 executed, such an expression will cause the entire containing function
53 to return with the value provided. This is different from a plain "eval
54 {}" block, in which circumstance only the "eval" itself would return,
55 not the entire function.
56
57 The body of a "try {}" block may contain loop control expressions
58 ("redo", "next", "last") which will have their usual effect on any
59 loops that the "try {}" block is contained by.
60
61 The parsing rules for the set of statements (the "try" block and its
62 associated "catch" and "finally") are such that they are parsed as a
63 self- contained statement. Because of this, there is no need to end
64 with a terminating semicolon.
65
66 Note (especially to users of Try::Tiny and similar) that the "try {}"
67 block itself does not necessarily stop exceptions thrown inside it from
68 propagating outside. It is the presence of a later "catch {}" block
69 which causes this to happen. A "try" with only a "finally" and no
70 "catch" will still propagate exceptions up to callers as normal.
71
72 catch
73 ...
74 catch {
75 STATEMENTS...
76 }
77
78 A "catch" statement provides a block of code to the preceeding "try"
79 statement that will be invoked in the case that the main block of code
80 throws an exception. The "catch" block can inspect the raised exception
81 by looking in $@ in the usual way.
82
83 Presence of this "catch" statement causes any exception thrown by the
84 preceeding "try" block to be non-fatal to the surrounding code. If the
85 "catch" block wishes to optionally handle some exceptions but not
86 others, it can re-raise it (or another exception) by calling "die" in
87 the usual manner.
88
89 As with "try", the body of a "catch {}" block may also contain a
90 "return" expression, which as before, has its usual meaning, causing
91 the entire containing function to return with the given value. The body
92 may also contain loop control expressions ("redo", "next" or "last")
93 which also have their usual effect.
94
95 If a "catch" statement is not given, then any exceptions raised by the
96 "try" block are raised to the caller in the usual way.
97
98 finally
99 ...
100 finally {
101 STATEMENTS...
102 }
103
104 A "finally" statement provides a block of code to the preceeding "try"
105 statement (or "try/catch" pair) which is executed afterwards, both in
106 the case of a normal execution or a thrown exception. This code block
107 may be used to provide whatever clean-up operations might be required
108 by preceeding code.
109
110 Because it is executed during a stack cleanup operation, a "finally {}"
111 block may not cause the containing function to return, or to alter the
112 return value of it. It also cannot see the containing function's @_
113 arguments array (though as it is block scoped within the function, it
114 will continue to share any normal lexical variables declared up until
115 that point). It is protected from disturbing the value of $@. If the
116 "finally {}" block code throws an exception, this will be printed as a
117 warning and discarded, leaving $@ containing the original exception, if
118 one existed.
119
121 · Value semantics. It would be nice if a "do {}"-wrapped "try" set
122 could yield a value, in the way other similar constructs can. For
123 example
124
125 my $x = do {
126 try { attempt(); "success" }
127 catch { "failure" }
128 };
129
130 A workaround for this current lack is to wrap the "try{} catch{}"
131 pair in an anonymous function which is then immediately executed:
132
133 my $x = sub {
134 try { attempt(); return "success" }
135 catch { return "failure" }
136 }->();
137
138 See also <https://rt.cpan.org/Ticket/Display.html?id=121267>.
139
141 There are already quite a number of modules on CPAN that provide a
142 "try/catch"-like syntax for Perl.
143
144 · Try
145
146 · TryCatch
147
148 · Try::Tiny
149
150 · Syntax::Feature::Try
151
152 They are compared here, by feature:
153
154 True syntax plugin
155 Like Try and Syntax::Feature::Try, this module is implemented as a true
156 syntax plugin, allowing it to provide new parsing rules not available
157 to simple functions. Most notably here it means that the resulting
158 combination does not need to end in a semicolon.
159
160 In comparison, Try::Tiny is plain perl and provides its functionality
161 using regular perl functions; as such its syntax requires the trailing
162 semicolon.
163
164 TryCatch is a hybrid that uses Devel::Declare to parse the syntax tree.
165
166 @_ in a try or catch block
167 Because the "try" and "catch" block code is contained in a true block
168 rather than an entire anonymous subroutine, invoking it does not
169 interfere with the @_ arguments array. Code inside these blocks can
170 interact with the containing function's array as before.
171
172 This feature is unique among these modules; none of the others listed
173 have this ability.
174
175 "return" in a try or catch block
176 Like TryCatch and Syntax::Feature::Try, the "return" statement has its
177 usual effect within a subroutine containing syntax provided by this
178 module. Namely, it causes the containing "sub" itself to return.
179
180 In comparison, using Try or Try::Tiny mean that a "return" statement
181 will only exit from the "try" block.
182
183 "next"/"last"/"redo" in a try or catch block
184 The loop control keywords of "next", "last" and "redo" have their usual
185 effect on dynamically contained loops.
186
187 Syntax::Feature::Try documents that these do not work there. The other
188 modules make no statement either way.
189
190 Value Semantics
191 Like Try and Syntax::Feature::Try, the syntax provided by this module
192 only works as a syntax-level statement and not an expression; you
193 cannot assign from the result of a "try" block. Additionally, final-
194 expression value semantics do not work, so it cannot be contained by a
195 "do" block to yield this value. See above for a workaround involving an
196 anonymous sub however.
197
198 In comparison, the behaviour implemented by Try::Tiny can be used as a
199 valued expression, such as assigned to a variable or returned to the
200 caller of its containing function.
201
202 "try" without "catch"
203 Like Syntax::Feature::Try, the syntax provided by this module allows a
204 "try" block to be followed by only a "finally" block, with no "catch".
205 In this case, exceptions thrown by code contained by the "try" are not
206 suppressed, instead they propagate as normal to callers. This matches
207 the behaviour familiar to Java or C++ programmers.
208
209 In comparison, the code provided by Try and Try::Tiny always suppress
210 exception propagation even without an actual "catch" block.
211
212 The TryCatch module does not allow a "try" block not followed by
213 "catch".
214
215 Typed "catch"
216 Like Try and Try::Tiny, this module makes no attempt to perform any
217 kind of typed dispatch to distinguish kinds of exception caught by
218 "catch" blocks.
219
220 TryCatch and Syntax::Feature::Try both attempt to provide a kind of
221 typed dispatch where different classes of exception are caught by
222 different blocks of code, or propagated up entirely to callers.
223
224 The author considers the lack of such ability in this module to be a
225 feature. That kind of dispatch on type matching of a controlling
226 expression is too useful a behaviour to be constrained to exception
227 catching. If the language is to provide such a facility, it should be
228 more universally applicable as a stand-alone independent ability.
229
231 Thread-safety at load time cannot be assured before perl 5.16
232 On perl versions 5.16 and above this module is thread-safe.
233
234 On perl version 5.14 this module is thread-safe provided that it is
235 "use"d before any additional threads are created.
236
237 However, when using 5.14 there is a race condition if this module is
238 loaded late in the program startup, after additional threads have been
239 created. This leads to the potential for it to be started up multiple
240 times concurrently, which creates data races when modifying internal
241 structures and likely leads to a segmentation fault, either during load
242 or soon after when more code is compiled.
243
244 As a workaround, for any such program that creates multiple threads,
245 loads additional code (such as dynamically-discovered plugins), and has
246 to run on 5.14, it should make sure to
247
248 use Syntax::Keyword::Try;
249
250 early on in startup, before it spins out any additional threads.
251
252 (See also <https://rt.cpan.org/Public/Bug/Display.html?id=123547>)
253
255 With thanks to "Zefram", "ilmari" and others from "irc.perl.org/#p5p"
256 for assisting with trickier bits of XS logic.
257
259 Paul Evans <leonerd@leonerd.org.uk>
260
261
262
263perl v5.28.1 2019-02-12 Syntax::Keyword::Try(3)