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