← Index
NYTProf Performance Profile   « line view »
For starman worker -M FindBin --max-requests 50 --workers 2 --user=kohadev-koha --group kohadev-koha --pid /var/run/koha/kohadev/plack.pid --daemonize --access-log /var/log/koha/kohadev/plack.log --error-log /var/log/koha/kohadev/plack-error.log -E deployment --socket /var/run/koha/kohadev/plack.sock /etc/koha/sites/kohadev/plack.psgi
  Run on Fri Jan 8 13:01:18 2016
Reported on Fri Jan 8 13:01:36 2016

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