1Try::Tiny(3) User Contributed Perl Documentation Try::Tiny(3)
2
3
4
6 Try::Tiny - Minimal try/catch with proper preservation of $@
7
9 version 0.30
10
12 You can use Try::Tiny's "try" and "catch" to expect and handle
13 exceptional conditions, avoiding quirks in Perl and common mistakes:
14
15 # handle errors with a catch handler
16 try {
17 die "foo";
18 } catch {
19 warn "caught error: $_"; # not $@
20 };
21
22 You can also use it like a standalone "eval" to catch and ignore any
23 error conditions. Obviously, this is an extreme measure not to be
24 undertaken lightly:
25
26 # just silence errors
27 try {
28 die "foo";
29 };
30
32 This module provides bare bones "try"/"catch"/"finally" statements that
33 are designed to minimize common mistakes with eval blocks, and NOTHING
34 else.
35
36 This is unlike TryCatch which provides a nice syntax and avoids adding
37 another call stack layer, and supports calling "return" from the "try"
38 block to return from the parent subroutine. These extra features come
39 at a cost of a few dependencies, namely Devel::Declare and Scope::Upper
40 which are occasionally problematic, and the additional catch filtering
41 uses Moose type constraints which may not be desirable either.
42
43 The main focus of this module is to provide simple and reliable error
44 handling for those having a hard time installing TryCatch, but who
45 still want to write correct "eval" blocks without 5 lines of
46 boilerplate each time.
47
48 It's designed to work as correctly as possible in light of the various
49 pathological edge cases (see "BACKGROUND") and to be compatible with
50 any style of error values (simple strings, references, objects,
51 overloaded objects, etc).
52
53 If the "try" block dies, it returns the value of the last statement
54 executed in the "catch" block, if there is one. Otherwise, it returns
55 "undef" in scalar context or the empty list in list context. The
56 following examples all assign "bar" to $x:
57
58 my $x = try { die "foo" } catch { "bar" };
59 my $x = try { die "foo" } || "bar";
60 my $x = (try { die "foo" }) // "bar";
61
62 my $x = eval { die "foo" } || "bar";
63
64 You can add "finally" blocks, yielding the following:
65
66 my $x;
67 try { die 'foo' } finally { $x = 'bar' };
68 try { die 'foo' } catch { warn "Got a die: $_" } finally { $x = 'bar' };
69
70 "finally" blocks are always executed making them suitable for cleanup
71 code which cannot be handled using local. You can add as many
72 "finally" blocks to a given "try" block as you like.
73
74 Note that adding a "finally" block without a preceding "catch" block
75 suppresses any errors. This behaviour is consistent with using a
76 standalone "eval", but it is not consistent with "try"/"finally"
77 patterns found in other programming languages, such as Java, Python,
78 Javascript or C#. If you learnt the "try"/"finally" pattern from one of
79 these languages, watch out for this.
80
82 All functions are exported by default using Exporter.
83
84 If you need to rename the "try", "catch" or "finally" keyword consider
85 using Sub::Import to get Sub::Exporter's flexibility.
86
87 try (&;@)
88 Takes one mandatory "try" subroutine, an optional "catch"
89 subroutine and "finally" subroutine.
90
91 The mandatory subroutine is evaluated in the context of an "eval"
92 block.
93
94 If no error occurred the value from the first block is returned,
95 preserving list/scalar context.
96
97 If there was an error and the second subroutine was given it will
98 be invoked with the error in $_ (localized) and as that block's
99 first and only argument.
100
101 $@ does not contain the error. Inside the "catch" block it has the
102 same value it had before the "try" block was executed.
103
104 Note that the error may be false, but if that happens the "catch"
105 block will still be invoked.
106
107 Once all execution is finished then the "finally" block, if given,
108 will execute.
109
110 catch (&;@)
111 Intended to be used in the second argument position of "try".
112
113 Returns a reference to the subroutine it was given but blessed as
114 "Try::Tiny::Catch" which allows try to decode correctly what to do
115 with this code reference.
116
117 catch { ... }
118
119 Inside the "catch" block the caught error is stored in $_, while
120 previous value of $@ is still available for use. This value may or
121 may not be meaningful depending on what happened before the "try",
122 but it might be a good idea to preserve it in an error stack.
123
124 For code that captures $@ when throwing new errors (i.e.
125 Class::Throwable), you'll need to do:
126
127 local $@ = $_;
128
129 finally (&;@)
130 try { ... }
131 catch { ... }
132 finally { ... };
133
134 Or
135
136 try { ... }
137 finally { ... };
138
139 Or even
140
141 try { ... }
142 finally { ... }
143 catch { ... };
144
145 Intended to be the second or third element of "try". "finally"
146 blocks are always executed in the event of a successful "try" or if
147 "catch" is run. This allows you to locate cleanup code which cannot
148 be done via "local()" e.g. closing a file handle.
149
150 When invoked, the "finally" block is passed the error that was
151 caught. If no error was caught, it is passed nothing. (Note that
152 the "finally" block does not localize $_ with the error, since
153 unlike in a "catch" block, there is no way to know if "$_ == undef"
154 implies that there were no errors.) In other words, the following
155 code does just what you would expect:
156
157 try {
158 die_sometimes();
159 } catch {
160 # ...code run in case of error
161 } finally {
162 if (@_) {
163 print "The try block died with: @_\n";
164 } else {
165 print "The try block ran without error.\n";
166 }
167 };
168
169 You must always do your own error handling in the "finally" block.
170 "Try::Tiny" will not do anything about handling possible errors
171 coming from code located in these blocks.
172
173 Furthermore exceptions in "finally" blocks are not trappable and
174 are unable to influence the execution of your program. This is due
175 to limitation of "DESTROY"-based scope guards, which "finally" is
176 implemented on top of. This may change in a future version of
177 Try::Tiny.
178
179 In the same way "catch()" blesses the code reference this
180 subroutine does the same except it bless them as
181 "Try::Tiny::Finally".
182
184 There are a number of issues with "eval".
185
186 Clobbering $@
187 When you run an "eval" block and it succeeds, $@ will be cleared,
188 potentially clobbering an error that is currently being caught.
189
190 This causes action at a distance, clearing previous errors your caller
191 may have not yet handled.
192
193 $@ must be properly localized before invoking "eval" in order to avoid
194 this issue.
195
196 More specifically, before Perl version 5.14.0 $@ was clobbered at the
197 beginning of the "eval", which also made it impossible to capture the
198 previous error before you die (for instance when making exception
199 objects with error stacks).
200
201 For this reason "try" will actually set $@ to its previous value (the
202 one available before entering the "try" block) in the beginning of the
203 "eval" block.
204
205 Localizing $@ silently masks errors
206 Inside an "eval" block, "die" behaves sort of like:
207
208 sub die {
209 $@ = $_[0];
210 return_undef_from_eval();
211 }
212
213 This means that if you were polite and localized $@ you can't die in
214 that scope, or your error will be discarded (printing "Something's
215 wrong" instead).
216
217 The workaround is very ugly:
218
219 my $error = do {
220 local $@;
221 eval { ... };
222 $@;
223 };
224
225 ...
226 die $error;
227
228 $@ might not be a true value
229 This code is wrong:
230
231 if ( $@ ) {
232 ...
233 }
234
235 because due to the previous caveats it may have been unset.
236
237 $@ could also be an overloaded error object that evaluates to false,
238 but that's asking for trouble anyway.
239
240 The classic failure mode (fixed in Perl 5.14.0) is:
241
242 sub Object::DESTROY {
243 eval { ... }
244 }
245
246 eval {
247 my $obj = Object->new;
248
249 die "foo";
250 };
251
252 if ( $@ ) {
253
254 }
255
256 In this case since "Object::DESTROY" is not localizing $@ but still
257 uses "eval", it will set $@ to "".
258
259 The destructor is called when the stack is unwound, after "die" sets $@
260 to "foo at Foo.pm line 42\n", so by the time "if ( $@ )" is evaluated
261 it has been cleared by "eval" in the destructor.
262
263 The workaround for this is even uglier than the previous ones. Even
264 though we can't save the value of $@ from code that doesn't localize,
265 we can at least be sure the "eval" was aborted due to an error:
266
267 my $failed = not eval {
268 ...
269
270 return 1;
271 };
272
273 This is because an "eval" that caught a "die" will always return a
274 false value.
275
277 Using Perl 5.10 you can use "Switch statements" in perlsyn (but please
278 don't, because that syntax has since been deprecated because there was
279 too much unexpected magical behaviour).
280
281 The "catch" block is invoked in a topicalizer context (like a "given"
282 block), but note that you can't return a useful value from "catch"
283 using the "when" blocks without an explicit "return".
284
285 This is somewhat similar to Perl 6's "CATCH" blocks. You can use it to
286 concisely match errors:
287
288 try {
289 require Foo;
290 } catch {
291 when (/^Can't locate .*?\.pm in \@INC/) { } # ignore
292 default { die $_ }
293 };
294
296 · @_ is not available within the "try" block, so you need to copy
297 your argument list. In case you want to work with argument values
298 directly via @_ aliasing (i.e. allow "$_[1] = "foo""), you need to
299 pass @_ by reference:
300
301 sub foo {
302 my ( $self, @args ) = @_;
303 try { $self->bar(@args) }
304 }
305
306 or
307
308 sub bar_in_place {
309 my $self = shift;
310 my $args = \@_;
311 try { $_ = $self->bar($_) for @$args }
312 }
313
314 · "return" returns from the "try" block, not from the parent sub
315 (note that this is also how "eval" works, but not how TryCatch
316 works):
317
318 sub parent_sub {
319 try {
320 die;
321 }
322 catch {
323 return;
324 };
325
326 say "this text WILL be displayed, even though an exception is thrown";
327 }
328
329 Instead, you should capture the return value:
330
331 sub parent_sub {
332 my $success = try {
333 die;
334 1;
335 };
336 return unless $success;
337
338 say "This text WILL NEVER appear!";
339 }
340 # OR
341 sub parent_sub_with_catch {
342 my $success = try {
343 die;
344 1;
345 }
346 catch {
347 # do something with $_
348 return undef; #see note
349 };
350 return unless $success;
351
352 say "This text WILL NEVER appear!";
353 }
354
355 Note that if you have a "catch" block, it must return "undef" for
356 this to work, since if a "catch" block exists, its return value is
357 returned in place of "undef" when an exception is thrown.
358
359 · "try" introduces another caller stack frame. Sub::Uplevel is not
360 used. Carp will not report this when using full stack traces,
361 though, because %Carp::Internal is used. This lack of magic is
362 considered a feature.
363
364 · The value of $_ in the "catch" block is not guaranteed to be the
365 value of the exception thrown ($@) in the "try" block. There is no
366 safe way to ensure this, since "eval" may be used unhygienically in
367 destructors. The only guarantee is that the "catch" will be called
368 if an exception is thrown.
369
370 · The return value of the "catch" block is not ignored, so if testing
371 the result of the expression for truth on success, be sure to
372 return a false value from the "catch" block:
373
374 my $obj = try {
375 MightFail->new;
376 } catch {
377 ...
378
379 return; # avoid returning a true value;
380 };
381
382 return unless $obj;
383
384 · $SIG{__DIE__} is still in effect.
385
386 Though it can be argued that $SIG{__DIE__} should be disabled
387 inside of "eval" blocks, since it isn't people have grown to rely
388 on it. Therefore in the interests of compatibility, "try" does not
389 disable $SIG{__DIE__} for the scope of the error throwing code.
390
391 · Lexical $_ may override the one set by "catch".
392
393 For example Perl 5.10's "given" form uses a lexical $_, creating
394 some confusing behavior:
395
396 given ($foo) {
397 when (...) {
398 try {
399 ...
400 } catch {
401 warn $_; # will print $foo, not the error
402 warn $_[0]; # instead, get the error like this
403 }
404 }
405 }
406
407 Note that this behavior was changed once again in Perl5 version 18
408 <https://metacpan.org/module/perldelta#given-now-aliases-the-
409 global-_>. However, since the entirety of lexical $_ is now
410 considered experimental
411 <https://metacpan.org/module/perldelta#Lexical-_-is-now-
412 experimental>, it is unclear whether the new version 18 behavior is
413 final.
414
416 TryCatch
417 Much more feature complete, more convenient semantics, but at the
418 cost of implementation complexity.
419
420 autodie
421 Automatic error throwing for builtin functions and more. Also
422 designed to work well with "given"/"when".
423
424 Throwable
425 A lightweight role for rolling your own exception classes.
426
427 Error
428 Exception object implementation with a "try" statement. Does not
429 localize $@.
430
431 Exception::Class::TryCatch
432 Provides a "catch" statement, but properly calling "eval" is your
433 responsibility.
434
435 The "try" keyword pushes $@ onto an error stack, avoiding some of
436 the issues with $@, but you still need to localize to prevent
437 clobbering.
438
440 I gave a lightning talk about this module, you can see the slides
441 (Firefox only):
442
443 <http://web.archive.org/web/20100628040134/http://nothingmuch.woobling.org/talks/takahashi.xul>
444
445 Or read the source:
446
447 <http://web.archive.org/web/20100305133605/http://nothingmuch.woobling.org/talks/yapc_asia_2009/try_tiny.yml>
448
450 Bugs may be submitted through the RT bug tracker
451 <https://rt.cpan.org/Public/Dist/Display.html?Name=Try-Tiny> (or
452 bug-Try-Tiny@rt.cpan.org <mailto:bug-Try-Tiny@rt.cpan.org>).
453
455 · יובל קוג'מן (Yuval Kogman) <nothingmuch@woobling.org>
456
457 · Jesse Luehrs <doy@tozt.net>
458
460 · Karen Etheridge <ether@cpan.org>
461
462 · Peter Rabbitson <ribasushi@cpan.org>
463
464 · Ricardo Signes <rjbs@cpan.org>
465
466 · Mark Fowler <mark@twoshortplanks.com>
467
468 · Graham Knop <haarg@haarg.org>
469
470 · Lukas Mai <l.mai@web.de>
471
472 · Aristotle Pagaltzis <pagaltzis@gmx.de>
473
474 · Dagfinn Ilmari Mannsåker <ilmari@ilmari.org>
475
476 · Paul Howarth <paul@city-fan.org>
477
478 · Rudolf Leermakers <rudolf@hatsuseno.org>
479
480 · anaxagoras <walkeraj@gmail.com>
481
482 · awalker <awalker@sourcefire.com>
483
484 · chromatic <chromatic@wgz.org>
485
486 · Alex <alex@koban.(none)>
487
488 · cm-perl <cm-perl@users.noreply.github.com>
489
490 · Andrew Yates <ayates@haddock.local>
491
492 · David Lowe <davidl@lokku.com>
493
494 · Glenn Fowler <cebjyre@cpan.org>
495
496 · Hans Dieter Pearcey <hdp@weftsoar.net>
497
498 · Jens Berthold <jens@jebecs.de>
499
500 · Jonathan Yu <JAWNSY@cpan.org>
501
502 · Marc Mims <marc@questright.com>
503
504 · Mark Stosberg <mark@stosberg.com>
505
506 · Pali <pali@cpan.org>
507
509 This software is Copyright (c) 2009 by יובל קוג'מן (Yuval Kogman).
510
511 This is free software, licensed under:
512
513 The MIT (X11) License
514
515
516
517perl v5.28.1 2017-12-21 Try::Tiny(3)