make this consistent
[p5sagit/Try-Tiny.git] / lib / Try / Tiny.pm
CommitLineData
3176feef 1package Try::Tiny;
12b7dc6c 2use 5.006;
3# ABSTRACT: minimal try/catch with proper preservation of $@
3176feef 4
5use strict;
f9d19a00 6use warnings;
3176feef 7
f9d19a00 8use base 'Exporter';
9our @EXPORT = our @EXPORT_OK = qw(try catch finally);
3176feef 10
f9d19a00 11use Carp;
6f114080 12$Carp::Internal{+__PACKAGE__}++;
13
5c9d800f 14BEGIN { eval "use Sub::Name; 1" or *{subname} = sub {1} }
15
7195fc08 16# Need to prototype as @ not $$ because of the way Perl evaluates the prototype.
17# Keeping it at $$ means you only ever get 1 sub because we need to eval in a list
18# context & not a scalar one
19
20sub try (&;@) {
8d2ee831 21 my ( $try, @code_refs ) = @_;
22
23 # we need to save this here, the eval block will be in scalar context due
24 # to $failed
25 my $wantarray = wantarray;
26
27 my ( $catch, @finally );
28
29 # find labeled blocks in the argument list.
30 # catch and finally tag the blocks by blessing a scalar reference to them.
31 foreach my $code_ref (@code_refs) {
8d2ee831 32
4c5b99d6 33 if ( ref($code_ref) eq 'Try::Tiny::Catch' ) {
9d0e0466 34 croak 'A try() may not be followed by multiple catch() blocks'
35 if $catch;
8d2ee831 36 $catch = ${$code_ref};
4c5b99d6 37 } elsif ( ref($code_ref) eq 'Try::Tiny::Finally' ) {
8d2ee831 38 push @finally, ${$code_ref};
39 } else {
4c5b99d6 40 croak(
41 'try() encountered an unexpected argument ('
42 . ( defined $code_ref ? $code_ref : 'undef' )
43 . ') - perhaps a missing semi-colon before or'
44 );
8d2ee831 45 }
46 }
47
2b0d579d 48 # FIXME consider using local $SIG{__DIE__} to accumulate all errors. It's
49 # not perfect, but we could provide a list of additional errors for
50 # $catch->();
51
5c9d800f 52 # name the blocks if we have Sub::Name installed
1131a831 53 my $caller = caller;
faa955ce 54 subname("${caller}::try {...} " => $try);
1131a831 55 subname("${caller}::catch {...} " => $catch) if $catch;
56 subname("${caller}::finally {...} " => $_) foreach @finally;
5c9d800f 57
8d2ee831 58 # save the value of $@ so we can set $@ back to it in the beginning of the eval
2b0d579d 59 # and restore $@ after the eval finishes
8d2ee831 60 my $prev_error = $@;
61
2b0d579d 62 my ( @ret, $error );
8d2ee831 63
2b0d579d 64 # failed will be true if the eval dies, because 1 will not be returned
65 # from the eval body
66 my $failed = not eval {
67 $@ = $prev_error;
8d2ee831 68
2b0d579d 69 # evaluate the try block in the correct context
70 if ( $wantarray ) {
71 @ret = $try->();
72 } elsif ( defined $wantarray ) {
73 $ret[0] = $try->();
74 } else {
75 $try->();
8d2ee831 76 };
77
2b0d579d 78 return 1; # properly set $fail to false
3db0dca6 79 };
2b0d579d 80
3db0dca6 81 # preserve the current error and reset the original value of $@
82 $error = $@;
2b0d579d 83 $@ = $prev_error;
8d2ee831 84
85 # set up a scope guard to invoke the finally block at the end
86 my @guards =
b611f396 87 map { Try::Tiny::ScopeGuard->_new($_, $failed ? $error : ()) }
88 @finally;
82ef0e61 89
8d2ee831 90 # at this point $failed contains a true value if the eval died, even if some
91 # destructor overwrote $@ as the eval was unwinding.
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) {
98 return $catch->($error);
99 }
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
103 }
104
105 return;
106 } else {
107 # no failure, $@ is back to what it was, everything is fine
108 return $wantarray ? @ret : $ret[0];
109 }
3176feef 110}
111
7195fc08 112sub catch (&;@) {
8d2ee831 113 my ( $block, @rest ) = @_;
7195fc08 114
d2ae14ad 115 croak 'Useless bare catch()' unless wantarray;
9d0e0466 116
8d2ee831 117 return (
118 bless(\$block, 'Try::Tiny::Catch'),
119 @rest,
120 );
3176feef 121}
122
7195fc08 123sub finally (&;@) {
8d2ee831 124 my ( $block, @rest ) = @_;
7195fc08 125
d2ae14ad 126 croak 'Useless bare finally()' unless wantarray;
9d0e0466 127
8d2ee831 128 return (
129 bless(\$block, 'Try::Tiny::Finally'),
130 @rest,
131 );
7195fc08 132}
3176feef 133
b611f396 134{
3ef3a4f0 135 package # hide from PAUSE
136 Try::Tiny::ScopeGuard;
b611f396 137
5f5e92c0 138 use constant UNSTABLE_DOLLARAT => ($] < '5.013002') ? 1 : 0;
139
b611f396 140 sub _new {
141 shift;
142 bless [ @_ ];
143 }
144
145 sub DESTROY {
5f5e92c0 146 my ($code, @args) = @{ $_[0] };
147
148 local $@ if UNSTABLE_DOLLARAT;
149 eval {
150 $code->(@args);
151 1;
152 } or do {
153 warn
154 "Execution of finally() block $code resulted in an exception, which "
155 . '*CAN NOT BE PROPAGATED* due to fundamental limitations of Perl. '
156 . 'Your program will continue as if this event never took place. '
157 . "Original exception text follows:\n\n"
158 . (defined $@ ? $@ : '$@ left undefined...')
159 . "\n"
160 ;
161 }
b611f396 162 }
82ef0e61 163}
164
3176feef 165__PACKAGE__
166
167__END__
168
169=pod
170
3176feef 171=head1 SYNOPSIS
172
a2358317 173You can use Try::Tiny's C<try> and C<catch> to expect and handle exceptional
174conditions, avoiding quirks in Perl and common mistakes:
175
8d2ee831 176 # handle errors with a catch handler
177 try {
178 die "foo";
179 } catch {
180 warn "caught error: $_"; # not $@
181 };
3176feef 182
b999823d 183You can also use it like a standalone C<eval> to catch and ignore any error
a2358317 184conditions. Obviously, this is an extreme measure not to be undertaken
185lightly:
186
8d2ee831 187 # just silence errors
188 try {
189 die "foo";
190 };
3176feef 191
192=head1 DESCRIPTION
193
7195fc08 194This module provides bare bones C<try>/C<catch>/C<finally> statements that are designed to
1f7c5af6 195minimize common mistakes with eval blocks, and NOTHING else.
3176feef 196
197This is unlike L<TryCatch> which provides a nice syntax and avoids adding
ad10a9e2 198another call stack layer, and supports calling C<return> from the C<try> block to
3176feef 199return from the parent subroutine. These extra features come at a cost of a few
200dependencies, namely L<Devel::Declare> and L<Scope::Upper> which are
1f7c5af6 201occasionally problematic, and the additional catch filtering uses L<Moose>
202type constraints which may not be desirable either.
3176feef 203
1f7c5af6 204The main focus of this module is to provide simple and reliable error handling
3176feef 205for those having a hard time installing L<TryCatch>, but who still want to
206write correct C<eval> blocks without 5 lines of boilerplate each time.
207
208It's designed to work as correctly as possible in light of the various
b999823d 209pathological edge cases (see L</BACKGROUND>) and to be compatible with any style
3176feef 210of error values (simple strings, references, objects, overloaded objects, etc).
211
ad10a9e2 212If the C<try> block dies, it returns the value of the last statement executed in
213the C<catch> block, if there is one. Otherwise, it returns C<undef> in scalar
c065237e 214context or the empty list in list context. The following examples all
ad10a9e2 215assign C<"bar"> to C<$x>:
a5cd5f73 216
8d2ee831 217 my $x = try { die "foo" } catch { "bar" };
218 my $x = try { die "foo" } || { "bar" };
219 my $x = (try { die "foo" }) // { "bar" };
a5cd5f73 220
8d2ee831 221 my $x = eval { die "foo" } || "bar";
a5cd5f73 222
ad10a9e2 223You can add C<finally> blocks, yielding the following:
7195fc08 224
8d2ee831 225 my $x;
226 try { die 'foo' } finally { $x = 'bar' };
227 try { die 'foo' } catch { warn "Got a die: $_" } finally { $x = 'bar' };
7195fc08 228
ad10a9e2 229C<finally> blocks are always executed making them suitable for cleanup code
230which cannot be handled using local. You can add as many C<finally> blocks to a
231given C<try> block as you like.
7195fc08 232
3176feef 233=head1 EXPORTS
234
1f7c5af6 235All functions are exported by default using L<Exporter>.
3176feef 236
7195fc08 237If you need to rename the C<try>, C<catch> or C<finally> keyword consider using
6157bcb8 238L<Sub::Import> to get L<Sub::Exporter>'s flexibility.
3176feef 239
240=over 4
241
7195fc08 242=item try (&;@)
3176feef 243
ad10a9e2 244Takes one mandatory C<try> subroutine, an optional C<catch> subroutine and C<finally>
7195fc08 245subroutine.
3176feef 246
247The mandatory subroutine is evaluated in the context of an C<eval> block.
248
1f7c5af6 249If no error occurred the value from the first block is returned, preserving
250list/scalar context.
3176feef 251
252If there was an error and the second subroutine was given it will be invoked
253with the error in C<$_> (localized) and as that block's first and only
254argument.
255
2dc64249 256C<$@> does B<not> contain the error. Inside the C<catch> block it has the same
257value it had before the C<try> block was executed.
258
1f7c5af6 259Note that the error may be false, but if that happens the C<catch> block will
1d64c1ad 260still be invoked.
3176feef 261
ad10a9e2 262Once all execution is finished then the C<finally> block, if given, will execute.
7195fc08 263
ae5ed1be 264=item catch (&;@)
1f7c5af6 265
266Intended to be used in the second argument position of C<try>.
3176feef 267
7195fc08 268Returns a reference to the subroutine it was given but blessed as
269C<Try::Tiny::Catch> which allows try to decode correctly what to do
270with this code reference.
3176feef 271
8d2ee831 272 catch { ... }
3176feef 273
ad10a9e2 274Inside the C<catch> block the caught error is stored in C<$_>, while previous
2dc64249 275value of C<$@> is still available for use. This value may or may not be
276meaningful depending on what happened before the C<try>, but it might be a good
277idea to preserve it in an error stack.
ac4f5f9f 278
0a0641f9 279For code that captures C<$@> when throwing new errors (i.e.
280L<Class::Throwable>), you'll need to do:
281
8d2ee831 282 local $@ = $_;
0a0641f9 283
ae5ed1be 284=item finally (&;@)
7195fc08 285
286 try { ... }
287 catch { ... }
288 finally { ... };
289
290Or
291
292 try { ... }
293 finally { ... };
294
295Or even
296
297 try { ... }
298 finally { ... }
299 catch { ... };
300
ad10a9e2 301Intended to be the second or third element of C<try>. C<finally> blocks are always
7195fc08 302executed in the event of a successful C<try> or if C<catch> is run. This allows
303you to locate cleanup code which cannot be done via C<local()> e.g. closing a file
304handle.
305
ad10a9e2 306When invoked, the C<finally> block is passed the error that was caught. If no
307error was caught, it is passed nothing. (Note that the C<finally> block does not
308localize C<$_> with the error, since unlike in a C<catch> block, there is no way
658a90e5 309to know if C<$_ == undef> implies that there were no errors.) In other words,
310the following code does just what you would expect:
d6e0f0df 311
312 try {
313 die_sometimes();
314 } catch {
315 # ...code run in case of error
316 } finally {
317 if (@_) {
318 print "The try block died with: @_\n";
319 } else {
320 print "The try block ran without error.\n";
321 }
322 };
323
ad10a9e2 324B<You must always do your own error handling in the C<finally> block>. C<Try::Tiny> will
7195fc08 325not do anything about handling possible errors coming from code located in these
326blocks.
327
5f5e92c0 328Furthermore B<exceptions in C<finally> blocks are not trappable and are unable
329to influence the execution of your program>. This is due to limitation of
330C<DESTROY>-based scope guards, which C<finally> is implemented on top of. This
331may change in a future version of Try::Tiny.
332
7195fc08 333In the same way C<catch()> blesses the code reference this subroutine does the same
334except it bless them as C<Try::Tiny::Finally>.
335
3176feef 336=back
337
338=head1 BACKGROUND
339
340There are a number of issues with C<eval>.
341
342=head2 Clobbering $@
343
ad10a9e2 344When you run an C<eval> block and it succeeds, C<$@> will be cleared, potentially
a717a876 345clobbering an error that is currently being caught.
3176feef 346
1f7c5af6 347This causes action at a distance, clearing previous errors your caller may have
348not yet handled.
349
350C<$@> must be properly localized before invoking C<eval> in order to avoid this
351issue.
3176feef 352
8e5b4441 353More specifically, C<$@> is clobbered at the beginning of the C<eval>, which
511c05ca 354also makes it impossible to capture the previous error before you die (for
355instance when making exception objects with error stacks).
356
2b0d579d 357For this reason C<try> will actually set C<$@> to its previous value (the one
358available before entering the C<try> block) in the beginning of the C<eval>
359block.
511c05ca 360
3176feef 361=head2 Localizing $@ silently masks errors
362
ad10a9e2 363Inside an C<eval> block, C<die> behaves sort of like:
3176feef 364
8d2ee831 365 sub die {
366 $@ = $_[0];
367 return_undef_from_eval();
368 }
3176feef 369
370This means that if you were polite and localized C<$@> you can't die in that
1f7c5af6 371scope, or your error will be discarded (printing "Something's wrong" instead).
3176feef 372
373The workaround is very ugly:
374
8d2ee831 375 my $error = do {
376 local $@;
377 eval { ... };
378 $@;
379 };
3176feef 380
8d2ee831 381 ...
382 die $error;
3176feef 383
384=head2 $@ might not be a true value
385
386This code is wrong:
387
8d2ee831 388 if ( $@ ) {
389 ...
390 }
3176feef 391
1f7c5af6 392because due to the previous caveats it may have been unset.
393
1d64c1ad 394C<$@> could also be an overloaded error object that evaluates to false, but
395that's asking for trouble anyway.
3176feef 396
397The classic failure mode is:
398
8d2ee831 399 sub Object::DESTROY {
400 eval { ... }
401 }
3176feef 402
8d2ee831 403 eval {
404 my $obj = Object->new;
3176feef 405
8d2ee831 406 die "foo";
407 };
3176feef 408
8d2ee831 409 if ( $@ ) {
3176feef 410
8d2ee831 411 }
3176feef 412
1f7c5af6 413In this case since C<Object::DESTROY> is not localizing C<$@> but still uses
1d64c1ad 414C<eval>, it will set C<$@> to C<"">.
3176feef 415
1f7c5af6 416The destructor is called when the stack is unwound, after C<die> sets C<$@> to
3176feef 417C<"foo at Foo.pm line 42\n">, so by the time C<if ( $@ )> is evaluated it has
1f7c5af6 418been cleared by C<eval> in the destructor.
3176feef 419
1f7c5af6 420The workaround for this is even uglier than the previous ones. Even though we
421can't save the value of C<$@> from code that doesn't localize, we can at least
ad10a9e2 422be sure the C<eval> was aborted due to an error:
3176feef 423
8d2ee831 424 my $failed = not eval {
425 ...
3176feef 426
8d2ee831 427 return 1;
428 };
3176feef 429
1f7c5af6 430This is because an C<eval> that caught a C<die> will always return a false
431value.
3176feef 432
f9b91e2c 433=head1 SHINY SYNTAX
3176feef 434
1f7c5af6 435Using Perl 5.10 you can use L<perlsyn/"Switch statements">.
3176feef 436
1f7c5af6 437The C<catch> block is invoked in a topicalizer context (like a C<given> block),
438but note that you can't return a useful value from C<catch> using the C<when>
27293e40 439blocks without an explicit C<return>.
3176feef 440
441This is somewhat similar to Perl 6's C<CATCH> blocks. You can use it to
442concisely match errors:
443
8d2ee831 444 try {
445 require Foo;
446 } catch {
447 when (/^Can't locate .*?\.pm in \@INC/) { } # ignore
448 default { die $_ }
449 };
3176feef 450
451=head1 CAVEATS
452
453=over 4
454
455=item *
456
013dca8f 457C<@_> is not available within the C<try> block, so you need to copy your
458arglist. In case you want to work with argument values directly via C<@_>
459aliasing (i.e. allow C<$_[1] = "foo">), you need to pass C<@_> by reference:
318cb1eb 460
8d2ee831 461 sub foo {
462 my ( $self, @args ) = @_;
463 try { $self->bar(@args) }
464 }
013dca8f 465
466or
467
8d2ee831 468 sub bar_in_place {
469 my $self = shift;
470 my $args = \@_;
471 try { $_ = $self->bar($_) for @$args }
472 }
318cb1eb 473
474=item *
475
476C<return> returns from the C<try> block, not from the parent sub (note that
477this is also how C<eval> works, but not how L<TryCatch> works):
478
6651956b 479 sub parent_sub {
8d2ee831 480 try {
481 die;
482 }
483 catch {
484 return;
485 };
6651956b 486
8d2ee831 487 say "this text WILL be displayed, even though an exception is thrown";
6651956b 488 }
489
490Instead, you should capture the return value:
491
492 sub parent_sub {
8d2ee831 493 my $success = try {
494 die;
495 1;
496 }
497 return unless $success;
6651956b 498
8d2ee831 499 say "This text WILL NEVER appear!";
6651956b 500 }
318cb1eb 501
ad10a9e2 502Note that if you have a C<catch> block, it must return C<undef> for this to work,
503since if a C<catch> block exists, its return value is returned in place of C<undef>
6651956b 504when an exception is thrown.
318cb1eb 505
506=item *
507
1f7c5af6 508C<try> introduces another caller stack frame. L<Sub::Uplevel> is not used. L<Carp>
c12e626f 509will not report this when using full stack traces, though, because
510C<%Carp::Internal> is used. This lack of magic is considered a feature.
3176feef 511
512=item *
513
57c50f41 514The value of C<$_> in the C<catch> block is not guaranteed to be the value of
515the exception thrown (C<$@>) in the C<try> block. There is no safe way to
516ensure this, since C<eval> may be used unhygenically in destructors. The only
517guarantee is that the C<catch> will be called if an exception is thrown.
3176feef 518
a5cd5f73 519=item *
520
521The return value of the C<catch> block is not ignored, so if testing the result
522of the expression for truth on success, be sure to return a false value from
523the C<catch> block:
524
8d2ee831 525 my $obj = try {
526 MightFail->new;
527 } catch {
528 ...
a5cd5f73 529
8d2ee831 530 return; # avoid returning a true value;
531 };
a5cd5f73 532
8d2ee831 533 return unless $obj;
a5cd5f73 534
eaca95b7 535=item *
536
537C<$SIG{__DIE__}> is still in effect.
538
539Though it can be argued that C<$SIG{__DIE__}> should be disabled inside of
540C<eval> blocks, since it isn't people have grown to rely on it. Therefore in
541the interests of compatibility, C<try> does not disable C<$SIG{__DIE__}> for
542the scope of the error throwing code.
543
cbfb5327 544=item *
545
546Lexical C<$_> may override the one set by C<catch>.
547
548For example Perl 5.10's C<given> form uses a lexical C<$_>, creating some
549confusing behavior:
550
8d2ee831 551 given ($foo) {
552 when (...) {
553 try {
554 ...
555 } catch {
556 warn $_; # will print $foo, not the error
557 warn $_[0]; # instead, get the error like this
558 }
559 }
560 }
cbfb5327 561
aaf0d61f 562Note that this behavior was changed once again in L<Perl5 version 18
563|https://metacpan.org/module/perldelta#given-now-aliases-the-global-_>.
564However, since the entirety of lexical C<$_> is now L<considired experimental
565|https://metacpan.org/module/perldelta#Lexical-_-is-now-experimental>, it
566is unclear whether the new version 18 behavior is final.
567
3176feef 568=back
569
570=head1 SEE ALSO
571
572=over 4
573
574=item L<TryCatch>
575
576Much more feature complete, more convenient semantics, but at the cost of
577implementation complexity.
578
9bc603cb 579=item L<autodie>
580
581Automatic error throwing for builtin functions and more. Also designed to
582work well with C<given>/C<when>.
583
f8227e43 584=item L<Throwable>
585
586A lightweight role for rolling your own exception classes.
587
3176feef 588=item L<Error>
589
590Exception object implementation with a C<try> statement. Does not localize
591C<$@>.
592
593=item L<Exception::Class::TryCatch>
594
595Provides a C<catch> statement, but properly calling C<eval> is your
596responsibility.
597
598The C<try> keyword pushes C<$@> onto an error stack, avoiding some of the
1d64c1ad 599issues with C<$@>, but you still need to localize to prevent clobbering.
3176feef 600
601=back
602
faecd5a0 603=head1 LIGHTNING TALK
604
605I gave a lightning talk about this module, you can see the slides (Firefox
606only):
607
9b3383e4 608L<http://web.archive.org/web/20100628040134/http://nothingmuch.woobling.org/talks/takahashi.xul>
faecd5a0 609
610Or read the source:
611
2245f1ae 612L<http://web.archive.org/web/20100305133605/http://nothingmuch.woobling.org/talks/yapc_asia_2009/try_tiny.yml>
faecd5a0 613
3176feef 614=head1 VERSION CONTROL
615
e5c5bdf1 616L<http://github.com/doy/try-tiny/>
3176feef 617
3176feef 618=cut
619