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