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