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