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

NAME

6       Try::Tiny - minimal try/catch with proper localization of $@
7

SYNOPSIS

9               # handle errors with a catch handler
10               try {
11                       die "foo";
12               } catch {
13                       warn "caught error: $_"; # not $@
14               };
15
16               # just silence errors
17               try {
18                       die "foo";
19               };
20

DESCRIPTION

22       This module provides bare bones "try"/"catch"/"finally" statements that
23       are designed to minimize common mistakes with eval blocks, and NOTHING
24       else.
25
26       This is unlike TryCatch which provides a nice syntax and avoids adding
27       another call stack layer, and supports calling "return" from the try
28       block to return from the parent subroutine. These extra features come
29       at a cost of a few dependencies, namely Devel::Declare and Scope::Upper
30       which are occasionally problematic, and the additional catch filtering
31       uses Moose type constraints which may not be desirable either.
32
33       The main focus of this module is to provide simple and reliable error
34       handling for those having a hard time installing TryCatch, but who
35       still want to write correct "eval" blocks without 5 lines of
36       boilerplate each time.
37
38       It's designed to work as correctly as possible in light of the various
39       pathological edge cases (see BACKGROUND) and to be compatible with any
40       style of error values (simple strings, references, objects, overloaded
41       objects, etc).
42
43       If the try block dies, it returns the value of the last statement
44       executed in the catch block, if there is one. Otherwise, it returns
45       "undef" in scalar context or the empty list in list context. The
46       following two examples both assign "bar" to $x.
47
48               my $x = try { die "foo" } catch { "bar" };
49
50               my $x = eval { die "foo" } || "bar";
51
52       You can add finally blocks making the following true.
53
54               my $x;
55               try { die 'foo' } finally { $x = 'bar' };
56               try { die 'foo' } catch { warn "Got a die: $_" } finally { $x = 'bar' };
57
58       Finally blocks are always executed making them suitable for cleanup
59       code which cannot be handled using local.  You can add as many finally
60       blocks to a given try block as you like.
61

EXPORTS

63       All functions are exported by default using Exporter.
64
65       If you need to rename the "try", "catch" or "finally" keyword consider
66       using Sub::Import to get Sub::Exporter's flexibility.
67
68       try (&;@)
69           Takes one mandatory try subroutine, an optional catch subroutine &
70           finally subroutine.
71
72           The mandatory subroutine is evaluated in the context of an "eval"
73           block.
74
75           If no error occurred the value from the first block is returned,
76           preserving list/scalar context.
77
78           If there was an error and the second subroutine was given it will
79           be invoked with the error in $_ (localized) and as that block's
80           first and only argument.
81
82           $@ does not contain the error. Inside the "catch" block it has the
83           same value it had before the "try" block was executed.
84
85           Note that the error may be false, but if that happens the "catch"
86           block will still be invoked.
87
88           Once all execution is finished then the finally block if given will
89           execute.
90
91       catch (&;$)
92           Intended to be used in the second argument position of "try".
93
94           Returns a reference to the subroutine it was given but blessed as
95           "Try::Tiny::Catch" which allows try to decode correctly what to do
96           with this code reference.
97
98                   catch { ... }
99
100           Inside the catch block the caught error is stored in $_, while
101           previous value of $@ is still available for use.  This value may or
102           may not be meaningful depending on what happened before the "try",
103           but it might be a good idea to preserve it in an error stack.
104
105           For code that captures $@ when throwing new errors (i.e.
106           Class::Throwable), you'll need to do:
107
108                   local $@ = $_;
109
110       finally (&;$)
111             try     { ... }
112             catch   { ... }
113             finally { ... };
114
115           Or
116
117             try     { ... }
118             finally { ... };
119
120           Or even
121
122             try     { ... }
123             finally { ... }
124             catch   { ... };
125
126           Intended to be the second or third element of "try". Finally blocks
127           are always executed in the event of a successful "try" or if
128           "catch" is run. This allows you to locate cleanup code which cannot
129           be done via "local()" e.g. closing a file handle.
130
131           When invoked, the finally block is passed the error that was
132           caught.  If no error was caught, it is passed nothing.  In other
133           words, the following code does just what you would expect:
134
135             try {
136               die_sometimes();
137             } catch {
138               # ...code run in case of error
139             } finally {
140               if (@_) {
141                 print "The try block died with: @_\n";
142               } else {
143                 print "The try block ran without error.\n";
144               }
145             };
146
147           You must always do your own error handling in the finally block.
148           "Try::Tiny" will not do anything about handling possible errors
149           coming from code located in these blocks.
150
151           In the same way "catch()" blesses the code reference this
152           subroutine does the same except it bless them as
153           "Try::Tiny::Finally".
154

BACKGROUND

156       There are a number of issues with "eval".
157
158   Clobbering $@
159       When you run an eval block and it succeeds, $@ will be cleared,
160       potentially clobbering an error that is currently being caught.
161
162       This causes action at a distance, clearing previous errors your caller
163       may have not yet handled.
164
165       $@ must be properly localized before invoking "eval" in order to avoid
166       this issue.
167
168       More specifically, $@ is clobbered at the beginning of the "eval",
169       which also makes it impossible to capture the previous error before you
170       die (for instance when making exception objects with error stacks).
171
172       For this reason "try" will actually set $@ to its previous value
173       (before the localization) in the beginning of the "eval" block.
174
175   Localizing $@ silently masks errors
176       Inside an eval block "die" behaves sort of like:
177
178               sub die {
179                       $@ = $_[0];
180                       return_undef_from_eval();
181               }
182
183       This means that if you were polite and localized $@ you can't die in
184       that scope, or your error will be discarded (printing "Something's
185       wrong" instead).
186
187       The workaround is very ugly:
188
189               my $error = do {
190                       local $@;
191                       eval { ... };
192                       $@;
193               };
194
195               ...
196               die $error;
197
198   $@ might not be a true value
199       This code is wrong:
200
201               if ( $@ ) {
202                       ...
203               }
204
205       because due to the previous caveats it may have been unset.
206
207       $@ could also be an overloaded error object that evaluates to false,
208       but that's asking for trouble anyway.
209
210       The classic failure mode is:
211
212               sub Object::DESTROY {
213                       eval { ... }
214               }
215
216               eval {
217                       my $obj = Object->new;
218
219                       die "foo";
220               };
221
222               if ( $@ ) {
223
224               }
225
226       In this case since "Object::DESTROY" is not localizing $@ but still
227       uses "eval", it will set $@ to "".
228
229       The destructor is called when the stack is unwound, after "die" sets $@
230       to "foo at Foo.pm line 42\n", so by the time "if ( $@ )" is evaluated
231       it has been cleared by "eval" in the destructor.
232
233       The workaround for this is even uglier than the previous ones. Even
234       though we can't save the value of $@ from code that doesn't localize,
235       we can at least be sure the eval was aborted due to an error:
236
237               my $failed = not eval {
238                       ...
239
240                       return 1;
241               };
242
243       This is because an "eval" that caught a "die" will always return a
244       false value.
245

SHINY SYNTAX

247       Using Perl 5.10 you can use "Switch statements" in perlsyn.
248
249       The "catch" block is invoked in a topicalizer context (like a "given"
250       block), but note that you can't return a useful value from "catch"
251       using the "when" blocks without an explicit "return".
252
253       This is somewhat similar to Perl 6's "CATCH" blocks. You can use it to
254       concisely match errors:
255
256               try {
257                       require Foo;
258               } catch {
259                       when (/^Can't locate .*?\.pm in \@INC/) { } # ignore
260                       default { die $_ }
261               };
262

CAVEATS

264       ·   @_ is not available within the "try" block, so you need to copy
265           your arglist. In case you want to work with argument values
266           directly via @_ aliasing (i.e. allow "$_[1] = "foo""), you need to
267           pass @_ by reference:
268
269                   sub foo {
270                           my ( $self, @args ) = @_;
271                           try { $self->bar(@args) }
272                   }
273
274           or
275
276                   sub bar_in_place {
277                           my $self = shift;
278                           my $args = \@_;
279                           try { $_ = $self->bar($_) for @$args }
280                   }
281
282       ·   "return" returns from the "try" block, not from the parent sub
283           (note that this is also how "eval" works, but not how TryCatch
284           works):
285
286                   sub bar {
287                           try { return "foo" };
288                           return "baz";
289                   }
290
291                   say bar(); # "baz"
292
293       ·   "try" introduces another caller stack frame. Sub::Uplevel is not
294           used. Carp will not report this when using full stack traces,
295           though, because %Carp::Internal is used. This lack of magic is
296           considered a feature.
297
298       ·   The value of $_ in the "catch" block is not guaranteed to be the
299           value of the exception thrown ($@) in the "try" block.  There is no
300           safe way to ensure this, since "eval" may be used unhygenically in
301           destructors.  The only guarantee is that the "catch" will be called
302           if an exception is thrown.
303
304       ·   The return value of the "catch" block is not ignored, so if testing
305           the result of the expression for truth on success, be sure to
306           return a false value from the "catch" block:
307
308                   my $obj = try {
309                           MightFail->new;
310                   } catch {
311                           ...
312
313                           return; # avoid returning a true value;
314                   };
315
316                   return unless $obj;
317
318       ·   $SIG{__DIE__} is still in effect.
319
320           Though it can be argued that $SIG{__DIE__} should be disabled
321           inside of "eval" blocks, since it isn't people have grown to rely
322           on it. Therefore in the interests of compatibility, "try" does not
323           disable $SIG{__DIE__} for the scope of the error throwing code.
324
325       ·   Lexical $_ may override the one set by "catch".
326
327           For example Perl 5.10's "given" form uses a lexical $_, creating
328           some confusing behavior:
329
330                   given ($foo) {
331                           when (...) {
332                                   try {
333                                           ...
334                                   } catch {
335                                           warn $_; # will print $foo, not the error
336                                           warn $_[0]; # instead, get the error like this
337                                   }
338                           }
339                   }
340

SEE ALSO

342       TryCatch
343           Much more feature complete, more convenient semantics, but at the
344           cost of implementation complexity.
345
346       autodie
347           Automatic error throwing for builtin functions and more. Also
348           designed to work well with "given"/"when".
349
350       Throwable
351           A lightweight role for rolling your own exception classes.
352
353       Error
354           Exception object implementation with a "try" statement. Does not
355           localize $@.
356
357       Exception::Class::TryCatch
358           Provides a "catch" statement, but properly calling "eval" is your
359           responsibility.
360
361           The "try" keyword pushes $@ onto an error stack, avoiding some of
362           the issues with $@, but you still need to localize to prevent
363           clobbering.
364

LIGHTNING TALK

366       I gave a lightning talk about this module, you can see the slides
367       (Firefox only):
368
369       <http://nothingmuch.woobling.org/talks/takahashi.xul?data=yapc_asia_2009/try_tiny.txt>
370
371       Or read the source:
372
373       <http://nothingmuch.woobling.org/talks/yapc_asia_2009/try_tiny.yml>
374

VERSION CONTROL

376       http://github.com/nothingmuch/try-tiny/
377       <http://github.com/nothingmuch/try-tiny/>
378

AUTHOR

380       Yuval Kogman <nothingmuch@woobling.org>
381
383               Copyright (c) 2009 Yuval Kogman. All rights reserved.
384               This program is free software; you can redistribute
385               it and/or modify it under the terms of the MIT license.
386
387
388
389perl v5.12.2                      2010-10-21                      Try::Tiny(3)
Impressum