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