version bump
[p5sagit/Try-Tiny.git] / lib / Try / Tiny.pm
CommitLineData
3176feef 1package Try::Tiny;
2
3use strict;
ae53da51 4#use warnings;
3176feef 5
ae53da51 6use vars qw(@EXPORT @EXPORT_OK $VERSION @ISA);
7
8BEGIN {
9 require Exporter;
10 @ISA = qw(Exporter);
11}
3176feef 12
5fb1c15f 13$VERSION = "0.06";
3176feef 14
15$VERSION = eval $VERSION;
16
7195fc08 17@EXPORT = @EXPORT_OK = qw(try catch finally);
3176feef 18
6f114080 19$Carp::Internal{+__PACKAGE__}++;
20
7195fc08 21# Need to prototype as @ not $$ because of the way Perl evaluates the prototype.
22# Keeping it at $$ means you only ever get 1 sub because we need to eval in a list
23# context & not a scalar one
24
25sub try (&;@) {
26 my ( $try, @code_refs ) = @_;
3176feef 27
28 # we need to save this here, the eval block will be in scalar context due
29 # to $failed
30 my $wantarray = wantarray;
31
7195fc08 32 my ( $catch, $finally );
33
34 # find labeled blocks in the argument list.
35 # catch and finally tag the blocks by blessing a scalar reference to them.
36 foreach my $code_ref (@code_refs) {
37 next unless $code_ref;
38
39 my $ref = ref($code_ref);
40
41 if ( $ref eq 'Try::Tiny::Catch' ) {
42 $catch = ${$code_ref};
43 } elsif ( $ref eq 'Try::Tiny::Finally' ) {
44 $finally = ${$code_ref};
45 } else {
46 use Carp;
47 confess("Unknown code ref type given '${ref}'. Check your usage & try again");
48 }
49 }
50
1d64c1ad 51 # save the value of $@ so we can set $@ back to it in the beginning of the eval
511c05ca 52 my $prev_error = $@;
53
3176feef 54 my ( @ret, $error, $failed );
55
1d64c1ad 56 # FIXME consider using local $SIG{__DIE__} to accumulate all errors. It's
3176feef 57 # not perfect, but we could provide a list of additional errors for
58 # $catch->();
59
60 {
61 # localize $@ to prevent clobbering of previous value by a successful
62 # eval.
63 local $@;
64
65 # failed will be true if the eval dies, because 1 will not be returned
66 # from the eval body
67 $failed = not eval {
511c05ca 68 $@ = $prev_error;
3176feef 69
70 # evaluate the try block in the correct context
71 if ( $wantarray ) {
72 @ret = $try->();
73 } elsif ( defined $wantarray ) {
74 $ret[0] = $try->();
75 } else {
76 $try->();
77 };
78
79 return 1; # properly set $fail to false
80 };
81
1d64c1ad 82 # copy $@ to $error; when we leave this scope, local $@ will revert $@
3176feef 83 # back to its previous value
84 $error = $@;
85 }
86
82ef0e61 87 # set up a scope guard to invoke the finally block at the end
88 my $guard = $finally && bless \$finally, "Try::Tiny::ScopeGuard";
89
1d64c1ad 90 # at this point $failed contains a true value if the eval died, even if some
91 # destructor overwrote $@ as the eval was unwinding.
3176feef 92 if ( $failed ) {
93 # if we got an error, invoke the catch block.
94 if ( $catch ) {
95 # This works like given($error), but is backwards compatible and
96 # sets $_ in the dynamic scope for the body of C<$catch>
97 for ($error) {
82ef0e61 98 return $catch->($error);
3176feef 99 }
44599111 100
101 # in case when() was used without an explicit return, the C<for>
102 # loop will be aborted and there's no useful return value
3176feef 103 }
44599111 104
105 return;
3176feef 106 } else {
107 # no failure, $@ is back to what it was, everything is fine
108 return $wantarray ? @ret : $ret[0];
109 }
110}
111
7195fc08 112sub catch (&;@) {
113 my ( $block, @rest ) = @_;
114
115 return (
116 bless(\$block, 'Try::Tiny::Catch'),
117 @rest,
118 );
3176feef 119}
120
7195fc08 121sub finally (&;@) {
122 my ( $block, @rest ) = @_;
123
124 return (
125 bless(\$block, 'Try::Tiny::Finally'),
126 @rest,
127 );
128}
3176feef 129
82ef0e61 130sub Try::Tiny::ScopeGuard::DESTROY {
131 my $self = shift;
132 $$self->();
133}
134
3176feef 135__PACKAGE__
136
137__END__
138
139=pod
140
141=head1 NAME
142
143Try::Tiny - minimal try/catch with proper localization of $@
144
145=head1 SYNOPSIS
146
147 # handle errors with a catch handler
148 try {
149 die "foo";
150 } catch {
2dc64249 151 warn "caught error: $_"; # not $@
3176feef 152 };
153
154 # just silence errors
155 try {
156 die "foo";
157 };
158
159=head1 DESCRIPTION
160
7195fc08 161This module provides bare bones C<try>/C<catch>/C<finally> statements that are designed to
1f7c5af6 162minimize common mistakes with eval blocks, and NOTHING else.
3176feef 163
164This is unlike L<TryCatch> which provides a nice syntax and avoids adding
165another call stack layer, and supports calling C<return> from the try block to
166return from the parent subroutine. These extra features come at a cost of a few
167dependencies, namely L<Devel::Declare> and L<Scope::Upper> which are
1f7c5af6 168occasionally problematic, and the additional catch filtering uses L<Moose>
169type constraints which may not be desirable either.
3176feef 170
1f7c5af6 171The main focus of this module is to provide simple and reliable error handling
3176feef 172for those having a hard time installing L<TryCatch>, but who still want to
173write correct C<eval> blocks without 5 lines of boilerplate each time.
174
175It's designed to work as correctly as possible in light of the various
176pathological edge cases (see L<BACKGROUND>) and to be compatible with any style
177of error values (simple strings, references, objects, overloaded objects, etc).
178
a5cd5f73 179If the try block dies, it returns the value of the last statement executed in
7195fc08 180the catch block, if there is one. Otherwise, it returns C<undef> in scalar
a5cd5f73 181context or the empty list in list context. The following two examples both
182assign C<"bar"> to C<$x>.
183
184 my $x = try { die "foo" } catch { "bar" };
185
186 my $x = eval { die "foo" } || "bar";
187
7195fc08 188You can add finally blocks making the following true.
189
190 my $x;
191 try { die 'foo' } finally { $x = 'bar' };
192 try { die 'foo' } catch { warn "Got a die: $_" } finally { $x = 'bar' };
193
194Finally blocks are always executed making them suitable for cleanup code
195which cannot be handled using local.
196
3176feef 197=head1 EXPORTS
198
1f7c5af6 199All functions are exported by default using L<Exporter>.
3176feef 200
7195fc08 201If you need to rename the C<try>, C<catch> or C<finally> keyword consider using
6157bcb8 202L<Sub::Import> to get L<Sub::Exporter>'s flexibility.
3176feef 203
204=over 4
205
7195fc08 206=item try (&;@)
3176feef 207
7195fc08 208Takes one mandatory try subroutine, an optional catch subroutine & finally
209subroutine.
3176feef 210
211The mandatory subroutine is evaluated in the context of an C<eval> block.
212
1f7c5af6 213If no error occurred the value from the first block is returned, preserving
214list/scalar context.
3176feef 215
216If there was an error and the second subroutine was given it will be invoked
217with the error in C<$_> (localized) and as that block's first and only
218argument.
219
2dc64249 220C<$@> does B<not> contain the error. Inside the C<catch> block it has the same
221value it had before the C<try> block was executed.
222
1f7c5af6 223Note that the error may be false, but if that happens the C<catch> block will
1d64c1ad 224still be invoked.
3176feef 225
7195fc08 226Once all execution is finished then the finally block if given will execute.
227
228=item catch (&;$)
1f7c5af6 229
230Intended to be used in the second argument position of C<try>.
3176feef 231
7195fc08 232Returns a reference to the subroutine it was given but blessed as
233C<Try::Tiny::Catch> which allows try to decode correctly what to do
234with this code reference.
3176feef 235
236 catch { ... }
237
2dc64249 238Inside the catch block the caught error is stored in C<$_>, while previous
239value of C<$@> is still available for use. This value may or may not be
240meaningful depending on what happened before the C<try>, but it might be a good
241idea to preserve it in an error stack.
ac4f5f9f 242
0a0641f9 243For code that captures C<$@> when throwing new errors (i.e.
244L<Class::Throwable>), you'll need to do:
245
246 local $@ = $_;
247
7195fc08 248=item finally (&;$)
249
250 try { ... }
251 catch { ... }
252 finally { ... };
253
254Or
255
256 try { ... }
257 finally { ... };
258
259Or even
260
261 try { ... }
262 finally { ... }
263 catch { ... };
264
265Intended to be the second or third element of C<try>. Finally blocks are always
266executed in the event of a successful C<try> or if C<catch> is run. This allows
267you to locate cleanup code which cannot be done via C<local()> e.g. closing a file
268handle.
269
270B<You must always do your own error handling in the finally block>. C<Try::Tiny> will
271not do anything about handling possible errors coming from code located in these
272blocks.
273
274In the same way C<catch()> blesses the code reference this subroutine does the same
275except it bless them as C<Try::Tiny::Finally>.
276
3176feef 277=back
278
279=head1 BACKGROUND
280
281There are a number of issues with C<eval>.
282
283=head2 Clobbering $@
284
285When you run an eval block and it succeeds, C<$@> will be cleared, potentially
a717a876 286clobbering an error that is currently being caught.
3176feef 287
1f7c5af6 288This causes action at a distance, clearing previous errors your caller may have
289not yet handled.
290
291C<$@> must be properly localized before invoking C<eval> in order to avoid this
292issue.
3176feef 293
8e5b4441 294More specifically, C<$@> is clobbered at the beginning of the C<eval>, which
511c05ca 295also makes it impossible to capture the previous error before you die (for
296instance when making exception objects with error stacks).
297
298For this reason C<try> will actually set C<$@> to its previous value (before
1d64c1ad 299the localization) in the beginning of the C<eval> block.
511c05ca 300
3176feef 301=head2 Localizing $@ silently masks errors
302
303Inside an eval block C<die> behaves sort of like:
304
305 sub die {
91254b51 306 $@ = $_[0];
3176feef 307 return_undef_from_eval();
308 }
309
310This means that if you were polite and localized C<$@> you can't die in that
1f7c5af6 311scope, or your error will be discarded (printing "Something's wrong" instead).
3176feef 312
313The workaround is very ugly:
314
315 my $error = do {
316 local $@;
317 eval { ... };
318 $@;
319 };
320
321 ...
322 die $error;
323
324=head2 $@ might not be a true value
325
326This code is wrong:
327
328 if ( $@ ) {
329 ...
330 }
331
1f7c5af6 332because due to the previous caveats it may have been unset.
333
1d64c1ad 334C<$@> could also be an overloaded error object that evaluates to false, but
335that's asking for trouble anyway.
3176feef 336
337The classic failure mode is:
338
339 sub Object::DESTROY {
340 eval { ... }
341 }
342
343 eval {
344 my $obj = Object->new;
345
346 die "foo";
347 };
348
349 if ( $@ ) {
350
351 }
352
1f7c5af6 353In this case since C<Object::DESTROY> is not localizing C<$@> but still uses
1d64c1ad 354C<eval>, it will set C<$@> to C<"">.
3176feef 355
1f7c5af6 356The destructor is called when the stack is unwound, after C<die> sets C<$@> to
3176feef 357C<"foo at Foo.pm line 42\n">, so by the time C<if ( $@ )> is evaluated it has
1f7c5af6 358been cleared by C<eval> in the destructor.
3176feef 359
1f7c5af6 360The workaround for this is even uglier than the previous ones. Even though we
361can't save the value of C<$@> from code that doesn't localize, we can at least
362be sure the eval was aborted due to an error:
3176feef 363
364 my $failed = not eval {
365 ...
366
367 return 1;
368 };
369
1f7c5af6 370This is because an C<eval> that caught a C<die> will always return a false
371value.
3176feef 372
f9b91e2c 373=head1 SHINY SYNTAX
3176feef 374
1f7c5af6 375Using Perl 5.10 you can use L<perlsyn/"Switch statements">.
3176feef 376
1f7c5af6 377The C<catch> block is invoked in a topicalizer context (like a C<given> block),
378but note that you can't return a useful value from C<catch> using the C<when>
27293e40 379blocks without an explicit C<return>.
3176feef 380
381This is somewhat similar to Perl 6's C<CATCH> blocks. You can use it to
382concisely match errors:
383
384 try {
385 require Foo;
386 } catch {
1f7c5af6 387 when (/^Can't locate .*?\.pm in \@INC/) { } # ignore
3176feef 388 default { die $_ }
deb85b37 389 };
3176feef 390
391=head1 CAVEATS
392
393=over 4
394
395=item *
396
318cb1eb 397C<@_> is not available, you need to name your args:
398
399 sub foo {
400 my ( $self, @args ) = @_;
401 try { $self->bar(@args) }
402 }
403
404=item *
405
406C<return> returns from the C<try> block, not from the parent sub (note that
407this is also how C<eval> works, but not how L<TryCatch> works):
408
409 sub bar {
410 try { return "foo" };
411 return "baz";
412 }
413
414 say bar(); # "baz"
415
416=item *
417
1f7c5af6 418C<try> introduces another caller stack frame. L<Sub::Uplevel> is not used. L<Carp>
c12e626f 419will not report this when using full stack traces, though, because
420C<%Carp::Internal> is used. This lack of magic is considered a feature.
3176feef 421
422=item *
423
57c50f41 424The value of C<$_> in the C<catch> block is not guaranteed to be the value of
425the exception thrown (C<$@>) in the C<try> block. There is no safe way to
426ensure this, since C<eval> may be used unhygenically in destructors. The only
427guarantee is that the C<catch> will be called if an exception is thrown.
3176feef 428
a5cd5f73 429=item *
430
431The return value of the C<catch> block is not ignored, so if testing the result
432of the expression for truth on success, be sure to return a false value from
433the C<catch> block:
434
435 my $obj = try {
436 MightFail->new;
437 } catch {
438 ...
439
440 return; # avoid returning a true value;
441 };
442
443 return unless $obj;
444
eaca95b7 445=item *
446
447C<$SIG{__DIE__}> is still in effect.
448
449Though it can be argued that C<$SIG{__DIE__}> should be disabled inside of
450C<eval> blocks, since it isn't people have grown to rely on it. Therefore in
451the interests of compatibility, C<try> does not disable C<$SIG{__DIE__}> for
452the scope of the error throwing code.
453
cbfb5327 454=item *
455
456Lexical C<$_> may override the one set by C<catch>.
457
458For example Perl 5.10's C<given> form uses a lexical C<$_>, creating some
459confusing behavior:
460
461 given ($foo) {
462 when (...) {
463 try {
464 ...
465 } catch {
466 warn $_; # will print $foo, not the error
467 warn $_[0]; # instead, get the error like this
468 }
469 }
470 }
471
3176feef 472=back
473
474=head1 SEE ALSO
475
476=over 4
477
478=item L<TryCatch>
479
480Much more feature complete, more convenient semantics, but at the cost of
481implementation complexity.
482
9bc603cb 483=item L<autodie>
484
485Automatic error throwing for builtin functions and more. Also designed to
486work well with C<given>/C<when>.
487
f8227e43 488=item L<Throwable>
489
490A lightweight role for rolling your own exception classes.
491
3176feef 492=item L<Error>
493
494Exception object implementation with a C<try> statement. Does not localize
495C<$@>.
496
497=item L<Exception::Class::TryCatch>
498
499Provides a C<catch> statement, but properly calling C<eval> is your
500responsibility.
501
502The C<try> keyword pushes C<$@> onto an error stack, avoiding some of the
1d64c1ad 503issues with C<$@>, but you still need to localize to prevent clobbering.
3176feef 504
505=back
506
faecd5a0 507=head1 LIGHTNING TALK
508
509I gave a lightning talk about this module, you can see the slides (Firefox
510only):
511
e9140680 512L<http://nothingmuch.woobling.org/talks/takahashi.xul?data=yapc_asia_2009/try_tiny.txt>
faecd5a0 513
514Or read the source:
515
516L<http://nothingmuch.woobling.org/talks/yapc_asia_2009/try_tiny.yml>
517
3176feef 518=head1 VERSION CONTROL
519
520L<http://github.com/nothingmuch/try-tiny/>
521
522=head1 AUTHOR
523
524Yuval Kogman E<lt>nothingmuch@woobling.orgE<gt>
525
526=head1 COPYRIGHT
527
c4e1eb12 528 Copyright (c) 2009 Yuval Kogman. All rights reserved.
3176feef 529 This program is free software; you can redistribute
c4e1eb12 530 it and/or modify it under the terms of the MIT license.
3176feef 531
532=cut
533