1Try::Tiny(3) User Contributed Perl Documentation Try::Tiny(3)
2
3
4
6 Try::Tiny - minimal try/catch with proper localization of $@
7
9 You can use Try::Tiny's "try" and "catch" to expect and handle
10 exceptional conditions, avoiding quirks in Perl and common mistakes:
11
12 # handle errors with a catch handler
13 try {
14 die "foo";
15 } catch {
16 warn "caught error: $_"; # not $@
17 };
18
19 You can also use it like a standalone "eval" to catch and ignore any
20 error conditions. Obviously, this is an extreme measure not to be
21 undertaken lightly:
22
23 # just silence errors
24 try {
25 die "foo";
26 };
27
29 This module provides bare bones "try"/"catch"/"finally" statements that
30 are designed to minimize common mistakes with eval blocks, and NOTHING
31 else.
32
33 This is unlike TryCatch which provides a nice syntax and avoids adding
34 another call stack layer, and supports calling "return" from the "try"
35 block to return from the parent subroutine. These extra features come
36 at a cost of a few dependencies, namely Devel::Declare and Scope::Upper
37 which are occasionally problematic, and the additional catch filtering
38 uses Moose type constraints which may not be desirable either.
39
40 The main focus of this module is to provide simple and reliable error
41 handling for those having a hard time installing TryCatch, but who
42 still want to write correct "eval" blocks without 5 lines of
43 boilerplate each time.
44
45 It's designed to work as correctly as possible in light of the various
46 pathological edge cases (see "BACKGROUND") and to be compatible with
47 any style of error values (simple strings, references, objects,
48 overloaded objects, etc).
49
50 If the "try" block dies, it returns the value of the last statement
51 executed in the "catch" block, if there is one. Otherwise, it returns
52 "undef" in scalar context or the empty list in list context. The
53 following examples all assign "bar" to $x:
54
55 my $x = try { die "foo" } catch { "bar" };
56 my $x = try { die "foo" } || { "bar" };
57 my $x = (try { die "foo" }) // { "bar" };
58
59 my $x = eval { die "foo" } || "bar";
60
61 You can add "finally" blocks, yielding the following:
62
63 my $x;
64 try { die 'foo' } finally { $x = 'bar' };
65 try { die 'foo' } catch { warn "Got a die: $_" } finally { $x = 'bar' };
66
67 "finally" blocks are always executed making them suitable for cleanup
68 code which cannot be handled using local. You can add as many
69 "finally" blocks to a given "try" block as you like.
70
72 All functions are exported by default using Exporter.
73
74 If you need to rename the "try", "catch" or "finally" keyword consider
75 using Sub::Import to get Sub::Exporter's flexibility.
76
77 try (&;@)
78 Takes one mandatory "try" subroutine, an optional "catch"
79 subroutine and "finally" subroutine.
80
81 The mandatory subroutine is evaluated in the context of an "eval"
82 block.
83
84 If no error occurred the value from the first block is returned,
85 preserving list/scalar context.
86
87 If there was an error and the second subroutine was given it will
88 be invoked with the error in $_ (localized) and as that block's
89 first and only argument.
90
91 $@ does not contain the error. Inside the "catch" block it has the
92 same value it had before the "try" block was executed.
93
94 Note that the error may be false, but if that happens the "catch"
95 block will still be invoked.
96
97 Once all execution is finished then the "finally" block, if given,
98 will execute.
99
100 catch (&;$)
101 Intended to be used in the second argument position of "try".
102
103 Returns a reference to the subroutine it was given but blessed as
104 "Try::Tiny::Catch" which allows try to decode correctly what to do
105 with this code reference.
106
107 catch { ... }
108
109 Inside the "catch" block the caught error is stored in $_, while
110 previous value of $@ is still available for use. This value may or
111 may not be meaningful depending on what happened before the "try",
112 but it might be a good idea to preserve it in an error stack.
113
114 For code that captures $@ when throwing new errors (i.e.
115 Class::Throwable), you'll need to do:
116
117 local $@ = $_;
118
119 finally (&;$)
120 try { ... }
121 catch { ... }
122 finally { ... };
123
124 Or
125
126 try { ... }
127 finally { ... };
128
129 Or even
130
131 try { ... }
132 finally { ... }
133 catch { ... };
134
135 Intended to be the second or third element of "try". "finally"
136 blocks are always executed in the event of a successful "try" or if
137 "catch" is run. This allows you to locate cleanup code which cannot
138 be done via "local()" e.g. closing a file handle.
139
140 When invoked, the "finally" block is passed the error that was
141 caught. If no error was caught, it is passed nothing. (Note that
142 the "finally" block does not localize $_ with the error, since
143 unlike in a "catch" block, there is no way to know if "$_ == undef"
144 implies that there were no errors.) In other words, the following
145 code does just what you would expect:
146
147 try {
148 die_sometimes();
149 } catch {
150 # ...code run in case of error
151 } finally {
152 if (@_) {
153 print "The try block died with: @_\n";
154 } else {
155 print "The try block ran without error.\n";
156 }
157 };
158
159 You must always do your own error handling in the "finally" block.
160 "Try::Tiny" will not do anything about handling possible errors
161 coming from code located in these blocks.
162
163 In the same way "catch()" blesses the code reference this
164 subroutine does the same except it bless them as
165 "Try::Tiny::Finally".
166
168 There are a number of issues with "eval".
169
170 Clobbering $@
171 When you run an "eval" block and it succeeds, $@ will be cleared,
172 potentially clobbering an error that is currently being caught.
173
174 This causes action at a distance, clearing previous errors your caller
175 may have not yet handled.
176
177 $@ must be properly localized before invoking "eval" in order to avoid
178 this issue.
179
180 More specifically, $@ is clobbered at the beginning of the "eval",
181 which also makes it impossible to capture the previous error before you
182 die (for instance when making exception objects with error stacks).
183
184 For this reason "try" will actually set $@ to its previous value
185 (before the localization) in the beginning of the "eval" block.
186
187 Localizing $@ silently masks errors
188 Inside an "eval" block, "die" behaves sort of like:
189
190 sub die {
191 $@ = $_[0];
192 return_undef_from_eval();
193 }
194
195 This means that if you were polite and localized $@ you can't die in
196 that scope, or your error will be discarded (printing "Something's
197 wrong" instead).
198
199 The workaround is very ugly:
200
201 my $error = do {
202 local $@;
203 eval { ... };
204 $@;
205 };
206
207 ...
208 die $error;
209
210 $@ might not be a true value
211 This code is wrong:
212
213 if ( $@ ) {
214 ...
215 }
216
217 because due to the previous caveats it may have been unset.
218
219 $@ could also be an overloaded error object that evaluates to false,
220 but that's asking for trouble anyway.
221
222 The classic failure mode is:
223
224 sub Object::DESTROY {
225 eval { ... }
226 }
227
228 eval {
229 my $obj = Object->new;
230
231 die "foo";
232 };
233
234 if ( $@ ) {
235
236 }
237
238 In this case since "Object::DESTROY" is not localizing $@ but still
239 uses "eval", it will set $@ to "".
240
241 The destructor is called when the stack is unwound, after "die" sets $@
242 to "foo at Foo.pm line 42\n", so by the time "if ( $@ )" is evaluated
243 it has been cleared by "eval" in the destructor.
244
245 The workaround for this is even uglier than the previous ones. Even
246 though we can't save the value of $@ from code that doesn't localize,
247 we can at least be sure the "eval" was aborted due to an error:
248
249 my $failed = not eval {
250 ...
251
252 return 1;
253 };
254
255 This is because an "eval" that caught a "die" will always return a
256 false value.
257
259 Using Perl 5.10 you can use "Switch statements" in perlsyn.
260
261 The "catch" block is invoked in a topicalizer context (like a "given"
262 block), but note that you can't return a useful value from "catch"
263 using the "when" blocks without an explicit "return".
264
265 This is somewhat similar to Perl 6's "CATCH" blocks. You can use it to
266 concisely match errors:
267
268 try {
269 require Foo;
270 } catch {
271 when (/^Can't locate .*?\.pm in \@INC/) { } # ignore
272 default { die $_ }
273 };
274
276 · @_ is not available within the "try" block, so you need to copy
277 your arglist. In case you want to work with argument values
278 directly via @_ aliasing (i.e. allow "$_[1] = "foo""), you need to
279 pass @_ by reference:
280
281 sub foo {
282 my ( $self, @args ) = @_;
283 try { $self->bar(@args) }
284 }
285
286 or
287
288 sub bar_in_place {
289 my $self = shift;
290 my $args = \@_;
291 try { $_ = $self->bar($_) for @$args }
292 }
293
294 · "return" returns from the "try" block, not from the parent sub
295 (note that this is also how "eval" works, but not how TryCatch
296 works):
297
298 sub parent_sub {
299 try {
300 die;
301 }
302 catch {
303 return;
304 };
305
306 say "this text WILL be displayed, even though an exception is thrown";
307 }
308
309 Instead, you should capture the return value:
310
311 sub parent_sub {
312 my $success = try {
313 die;
314 1;
315 }
316 return unless $success;
317
318 say "This text WILL NEVER appear!";
319 }
320
321 Note that if you have a "catch" block, it must return "undef" for
322 this to work, since if a "catch" block exists, its return value is
323 returned in place of "undef" when an exception is thrown.
324
325 · "try" introduces another caller stack frame. Sub::Uplevel is not
326 used. Carp will not report this when using full stack traces,
327 though, because %Carp::Internal is used. This lack of magic is
328 considered a feature.
329
330 · The value of $_ in the "catch" block is not guaranteed to be the
331 value of the exception thrown ($@) in the "try" block. There is no
332 safe way to ensure this, since "eval" may be used unhygenically in
333 destructors. The only guarantee is that the "catch" will be called
334 if an exception is thrown.
335
336 · The return value of the "catch" block is not ignored, so if testing
337 the result of the expression for truth on success, be sure to
338 return a false value from the "catch" block:
339
340 my $obj = try {
341 MightFail->new;
342 } catch {
343 ...
344
345 return; # avoid returning a true value;
346 };
347
348 return unless $obj;
349
350 · $SIG{__DIE__} is still in effect.
351
352 Though it can be argued that $SIG{__DIE__} should be disabled
353 inside of "eval" blocks, since it isn't people have grown to rely
354 on it. Therefore in the interests of compatibility, "try" does not
355 disable $SIG{__DIE__} for the scope of the error throwing code.
356
357 · Lexical $_ may override the one set by "catch".
358
359 For example Perl 5.10's "given" form uses a lexical $_, creating
360 some confusing behavior:
361
362 given ($foo) {
363 when (...) {
364 try {
365 ...
366 } catch {
367 warn $_; # will print $foo, not the error
368 warn $_[0]; # instead, get the error like this
369 }
370 }
371 }
372
374 TryCatch
375 Much more feature complete, more convenient semantics, but at the
376 cost of implementation complexity.
377
378 autodie
379 Automatic error throwing for builtin functions and more. Also
380 designed to work well with "given"/"when".
381
382 Throwable
383 A lightweight role for rolling your own exception classes.
384
385 Error
386 Exception object implementation with a "try" statement. Does not
387 localize $@.
388
389 Exception::Class::TryCatch
390 Provides a "catch" statement, but properly calling "eval" is your
391 responsibility.
392
393 The "try" keyword pushes $@ onto an error stack, avoiding some of
394 the issues with $@, but you still need to localize to prevent
395 clobbering.
396
398 I gave a lightning talk about this module, you can see the slides
399 (Firefox only):
400
401 <http://nothingmuch.woobling.org/talks/takahashi.xul?data=yapc_asia_2009/try_tiny.txt>
402
403 Or read the source:
404
405 <http://nothingmuch.woobling.org/talks/yapc_asia_2009/try_tiny.yml>
406
408 <http://github.com/nothingmuch/try-tiny/>
409
411 Yuval Kogman <nothingmuch@woobling.org>
412
414 Copyright (c) 2009 Yuval Kogman. All rights reserved.
415 This program is free software; you can redistribute
416 it and/or modify it under the terms of the MIT license.
417
418
419
420perl v5.16.3 2013-01-02 Try::Tiny(3)