1Try::Tiny(3)          User Contributed Perl Documentation         Try::Tiny(3)
2
3
4

NAME

6       Try::Tiny - Minimal try/catch with proper preservation of $@
7

VERSION

9       version 0.31
10

SYNOPSIS

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

DESCRIPTION

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 learned the "try"/"finally" pattern from one
79       of these languages, watch out for this.
80

EXPORTS

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 subroutine
180           does the same except it bless them as "Try::Tiny::Finally".
181

BACKGROUND

183       There are a number of issues with "eval".
184
185   Clobbering $@
186       When you run an "eval" block and it succeeds, $@ will be cleared,
187       potentially clobbering an error that is currently being caught.
188
189       This causes action at a distance, clearing previous errors your caller
190       may have not yet handled.
191
192       $@ must be properly localized before invoking "eval" in order to avoid
193       this issue.
194
195       More specifically, before Perl version 5.14.0 $@ was clobbered at the
196       beginning of the "eval", which also made it impossible to capture the
197       previous error before you die (for instance when making exception
198       objects with error stacks).
199
200       For this reason "try" will actually set $@ to its previous value (the
201       one available before entering the "try" block) in the beginning of the
202       "eval" block.
203
204   Localizing $@ silently masks errors
205       Inside an "eval" block, "die" behaves sort of like:
206
207         sub die {
208           $@ = $_[0];
209           return_undef_from_eval();
210         }
211
212       This means that if you were polite and localized $@ you can't die in
213       that scope, or your error will be discarded (printing "Something's
214       wrong" instead).
215
216       The workaround is very ugly:
217
218         my $error = do {
219           local $@;
220           eval { ... };
221           $@;
222         };
223
224         ...
225         die $error;
226
227   $@ might not be a true value
228       This code is wrong:
229
230         if ( $@ ) {
231           ...
232         }
233
234       because due to the previous caveats it may have been unset.
235
236       $@ could also be an overloaded error object that evaluates to false,
237       but that's asking for trouble anyway.
238
239       The classic failure mode (fixed in Perl 5.14.0) is:
240
241         sub Object::DESTROY {
242           eval { ... }
243         }
244
245         eval {
246           my $obj = Object->new;
247
248           die "foo";
249         };
250
251         if ( $@ ) {
252
253         }
254
255       In this case since "Object::DESTROY" is not localizing $@ but still
256       uses "eval", it will set $@ to "".
257
258       The destructor is called when the stack is unwound, after "die" sets $@
259       to "foo at Foo.pm line 42\n", so by the time "if ( $@ )" is evaluated
260       it has been cleared by "eval" in the destructor.
261
262       The workaround for this is even uglier than the previous ones. Even
263       though we can't save the value of $@ from code that doesn't localize,
264       we can at least be sure the "eval" was aborted due to an error:
265
266         my $failed = not eval {
267           ...
268
269           return 1;
270         };
271
272       This is because an "eval" that caught a "die" will always return a
273       false value.
274

ALTERNATE SYNTAX

276       Using Perl 5.10 you can use "Switch statements" in perlsyn (but please
277       don't, because that syntax has since been deprecated because there was
278       too much unexpected magical behaviour).
279
280       The "catch" block is invoked in a topicalizer context (like a "given"
281       block), but note that you can't return a useful value from "catch"
282       using the "when" blocks without an explicit "return".
283
284       This is somewhat similar to Perl 6's "CATCH" blocks. You can use it to
285       concisely match errors:
286
287         try {
288           require Foo;
289         } catch {
290           when (/^Can't locate .*?\.pm in \@INC/) { } # ignore
291           default { die $_ }
292         };
293

CAVEATS

295       •   @_ is not available within the "try" block, so you need to copy
296           your argument list. In case you want to work with argument values
297           directly via @_ aliasing (i.e. allow "$_[1] = "foo""), you need to
298           pass @_ by reference:
299
300             sub foo {
301               my ( $self, @args ) = @_;
302               try { $self->bar(@args) }
303             }
304
305           or
306
307             sub bar_in_place {
308               my $self = shift;
309               my $args = \@_;
310               try { $_ = $self->bar($_) for @$args }
311             }
312
313       •   "return" returns from the "try" block, not from the parent sub
314           (note that this is also how "eval" works, but not how TryCatch
315           works):
316
317             sub parent_sub {
318               try {
319                 die;
320               }
321               catch {
322                 return;
323               };
324
325               say "this text WILL be displayed, even though an exception is thrown";
326             }
327
328           Instead, you should capture the return value:
329
330             sub parent_sub {
331               my $success = try {
332                 die;
333                 1;
334               };
335               return unless $success;
336
337               say "This text WILL NEVER appear!";
338             }
339             # OR
340             sub parent_sub_with_catch {
341               my $success = try {
342                 die;
343                 1;
344               }
345               catch {
346                 # do something with $_
347                 return undef; #see note
348               };
349               return unless $success;
350
351               say "This text WILL NEVER appear!";
352             }
353
354           Note that if you have a "catch" block, it must return "undef" for
355           this to work, since if a "catch" block exists, its return value is
356           returned in place of "undef" when an exception is thrown.
357
358       •   "try" introduces another caller stack frame. Sub::Uplevel is not
359           used. Carp will not report this when using full stack traces,
360           though, because %Carp::Internal is used. This lack of magic is
361           considered a feature.
362
363       •   The value of $_ in the "catch" block is not guaranteed to be the
364           value of the exception thrown ($@) in the "try" block.  There is no
365           safe way to ensure this, since "eval" may be used unhygienically in
366           destructors.  The only guarantee is that the "catch" will be called
367           if an exception is thrown.
368
369       •   The return value of the "catch" block is not ignored, so if testing
370           the result of the expression for truth on success, be sure to
371           return a false value from the "catch" block:
372
373             my $obj = try {
374               MightFail->new;
375             } catch {
376               ...
377
378               return; # avoid returning a true value;
379             };
380
381             return unless $obj;
382
383       •   $SIG{__DIE__} is still in effect.
384
385           Though it can be argued that $SIG{__DIE__} should be disabled
386           inside of "eval" blocks, since it isn't people have grown to rely
387           on it. Therefore in the interests of compatibility, "try" does not
388           disable $SIG{__DIE__} for the scope of the error throwing code.
389
390       •   Lexical $_ may override the one set by "catch".
391
392           For example Perl 5.10's "given" form uses a lexical $_, creating
393           some confusing behavior:
394
395             given ($foo) {
396               when (...) {
397                 try {
398                   ...
399                 } catch {
400                   warn $_; # will print $foo, not the error
401                   warn $_[0]; # instead, get the error like this
402                 }
403               }
404             }
405
406           Note that this behavior was changed once again in Perl5 version 18
407           <https://metacpan.org/module/perldelta#given-now-aliases-the-
408           global-_>.  However, since the entirety of lexical $_ is now
409           considered experimental
410            <https://metacpan.org/module/perldelta#Lexical-_-is-now-
411           experimental>, it is unclear whether the new version 18 behavior is
412           final.
413

SEE ALSO

415       Syntax::Keyword::Try
416           Only available on perls >= 5.14, with a slightly different syntax
417           (e.g. no trailing ";" because it's actually a keyword, not a sub,
418           but this means you can "return" and "next" within it). Use
419           Feature::Compat::Try to automatically switch to the native "try"
420           syntax in newer perls (when available). See also Try Catch
421           Exception Handling.
422
423       TryCatch
424           Much more feature complete, more convenient semantics, but at the
425           cost of implementation complexity.
426
427       autodie
428           Automatic error throwing for builtin functions and more. Also
429           designed to work well with "given"/"when".
430
431       Throwable
432           A lightweight role for rolling your own exception classes.
433
434       Error
435           Exception object implementation with a "try" statement. Does not
436           localize $@.
437
438       Exception::Class::TryCatch
439           Provides a "catch" statement, but properly calling "eval" is your
440           responsibility.
441
442           The "try" keyword pushes $@ onto an error stack, avoiding some of
443           the issues with $@, but you still need to localize to prevent
444           clobbering.
445

LIGHTNING TALK

447       I gave a lightning talk about this module, you can see the slides
448       (Firefox only):
449
450       <http://web.archive.org/web/20100628040134/http://nothingmuch.woobling.org/talks/takahashi.xul>
451
452       Or read the source:
453
454       <http://web.archive.org/web/20100305133605/http://nothingmuch.woobling.org/talks/yapc_asia_2009/try_tiny.yml>
455

SUPPORT

457       Bugs may be submitted through the RT bug tracker
458       <https://rt.cpan.org/Public/Dist/Display.html?Name=Try-Tiny> (or
459       bug-Try-Tiny@rt.cpan.org <mailto:bug-Try-Tiny@rt.cpan.org>).
460

AUTHORS

462       •   יובל קוג'מן (Yuval Kogman) <nothingmuch@woobling.org>
463
464       •   Jesse Luehrs <doy@tozt.net>
465

CONTRIBUTORS

467       •   Karen Etheridge <ether@cpan.org>
468
469       •   Peter Rabbitson <ribasushi@cpan.org>
470
471       •   Ricardo Signes <rjbs@cpan.org>
472
473       •   Mark Fowler <mark@twoshortplanks.com>
474
475       •   Graham Knop <haarg@haarg.org>
476
477       •   Aristotle Pagaltzis <pagaltzis@gmx.de>
478
479       •   Dagfinn Ilmari Mannsåker <ilmari@ilmari.org>
480
481       •   Lukas Mai <l.mai@web.de>
482
483       •   Alex <alex@koban.(none)>
484
485       •   anaxagoras <walkeraj@gmail.com>
486
487       •   Andrew Yates <ayates@haddock.local>
488
489       •   awalker <awalker@sourcefire.com>
490
491       •   chromatic <chromatic@wgz.org>
492
493       •   cm-perl <cm-perl@users.noreply.github.com>
494
495       •   David Lowe <davidl@lokku.com>
496
497       •   Glenn Fowler <cebjyre@cpan.org>
498
499       •   Hans Dieter Pearcey <hdp@weftsoar.net>
500
501       •   Jens Berthold <jens@jebecs.de>
502
503       •   Jonathan Yu <JAWNSY@cpan.org>
504
505       •   Marc Mims <marc@questright.com>
506
507       •   Mark Stosberg <mark@stosberg.com>
508
509       •   Pali <pali@cpan.org>
510
511       •   Paul Howarth <paul@city-fan.org>
512
513       •   Rudolf Leermakers <rudolf@hatsuseno.org>
514
516       This software is Copyright (c) 2009 by יובל קוג'מן (Yuval Kogman).
517
518       This is free software, licensed under:
519
520         The MIT (X11) License
521
522
523
524perl v5.36.0                      2023-01-20                      Try::Tiny(3)
Impressum