6 use vars qw(@EXPORT @EXPORT_OK $VERSION @ISA);
15 $VERSION = eval $VERSION;
17 @EXPORT = @EXPORT_OK = qw(try catch);
19 $Carp::Internal{+__PACKAGE__}++;
22 my ( $try, $catch ) = @_;
24 # we need to save this here, the eval block will be in scalar context due
26 my $wantarray = wantarray;
28 # save the value of $@ so we can set $@ back to it in the beginning of the eval
31 my ( @ret, $error, $failed );
33 # FIXME consider using local $SIG{__DIE__} to accumulate all errors. It's
34 # not perfect, but we could provide a list of additional errors for
38 # localize $@ to prevent clobbering of previous value by a successful
42 # failed will be true if the eval dies, because 1 will not be returned
47 # evaluate the try block in the correct context
50 } elsif ( defined $wantarray ) {
56 return 1; # properly set $fail to false
59 # copy $@ to $error; when we leave this scope, local $@ will revert $@
60 # back to its previous value
64 # at this point $failed contains a true value if the eval died, even if some
65 # destructor overwrote $@ as the eval was unwinding.
67 # if we got an error, invoke the catch block.
69 # This works like given($error), but is backwards compatible and
70 # sets $_ in the dynamic scope for the body of C<$catch>
72 return $catch->($error);
75 # in case when() was used without an explicit return, the C<for>
76 # loop will be aborted and there's no useful return value
81 # no failure, $@ is back to what it was, everything is fine
82 return $wantarray ? @ret : $ret[0];
99 Try::Tiny - minimal try/catch with proper localization of $@
103 # handle errors with a catch handler
107 warn "caught error: $_";
110 # just silence errors
117 This module provides bare bones C<try>/C<catch> statements that are designed to
118 minimize common mistakes with eval blocks, and NOTHING else.
120 This is unlike L<TryCatch> which provides a nice syntax and avoids adding
121 another call stack layer, and supports calling C<return> from the try block to
122 return from the parent subroutine. These extra features come at a cost of a few
123 dependencies, namely L<Devel::Declare> and L<Scope::Upper> which are
124 occasionally problematic, and the additional catch filtering uses L<Moose>
125 type constraints which may not be desirable either.
127 The main focus of this module is to provide simple and reliable error handling
128 for those having a hard time installing L<TryCatch>, but who still want to
129 write correct C<eval> blocks without 5 lines of boilerplate each time.
131 It's designed to work as correctly as possible in light of the various
132 pathological edge cases (see L<BACKGROUND>) and to be compatible with any style
133 of error values (simple strings, references, objects, overloaded objects, etc).
135 If the try block dies, it returns the value of the last statement executed in
136 the catch block, if there is one. Otherwise, it returns C<undef> in scalar
137 context or the empty list in list context. The following two examples both
138 assign C<"bar"> to C<$x>.
140 my $x = try { die "foo" } catch { "bar" };
142 my $x = eval { die "foo" } || "bar";
146 All functions are exported by default using L<Exporter>.
148 If you need to rename the C<try> or C<catch> keyword consider using
149 L<Sub::Import> to get L<Sub::Exporter>'s flexibility.
155 Takes one mandatory try subroutine and one optional catch subroutine.
157 The mandatory subroutine is evaluated in the context of an C<eval> block.
159 If no error occurred the value from the first block is returned, preserving
162 If there was an error and the second subroutine was given it will be invoked
163 with the error in C<$_> (localized) and as that block's first and only
166 Note that the error may be false, but if that happens the C<catch> block will
171 Intended to be used in the second argument position of C<try>.
173 Just returns the subroutine it was given.
181 Inside the catch block the previous value of C<$@> is still available for use.
182 This value may or may not be meaningful depending on what happened before the
183 C<try>, but it might be a good idea to preserve it in an error stack.
189 There are a number of issues with C<eval>.
193 When you run an eval block and it succeeds, C<$@> will be cleared, potentially
194 clobbering an error that is currently being caught.
196 This causes action at a distance, clearing previous errors your caller may have
199 C<$@> must be properly localized before invoking C<eval> in order to avoid this
202 More specifically, C<$@> is clobbered at the begining of the C<eval>, which
203 also makes it impossible to capture the previous error before you die (for
204 instance when making exception objects with error stacks).
206 For this reason C<try> will actually set C<$@> to its previous value (before
207 the localization) in the beginning of the C<eval> block.
209 =head2 Localizing $@ silently masks errors
211 Inside an eval block C<die> behaves sort of like:
215 return_undef_from_eval();
218 This means that if you were polite and localized C<$@> you can't die in that
219 scope, or your error will be discarded (printing "Something's wrong" instead).
221 The workaround is very ugly:
232 =head2 $@ might not be a true value
240 because due to the previous caveats it may have been unset.
242 C<$@> could also be an overloaded error object that evaluates to false, but
243 that's asking for trouble anyway.
245 The classic failure mode is:
247 sub Object::DESTROY {
252 my $obj = Object->new;
261 In this case since C<Object::DESTROY> is not localizing C<$@> but still uses
262 C<eval>, it will set C<$@> to C<"">.
264 The destructor is called when the stack is unwound, after C<die> sets C<$@> to
265 C<"foo at Foo.pm line 42\n">, so by the time C<if ( $@ )> is evaluated it has
266 been cleared by C<eval> in the destructor.
268 The workaround for this is even uglier than the previous ones. Even though we
269 can't save the value of C<$@> from code that doesn't localize, we can at least
270 be sure the eval was aborted due to an error:
272 my $failed = not eval {
278 This is because an C<eval> that caught a C<die> will always return a false
283 Using Perl 5.10 you can use L<perlsyn/"Switch statements">.
285 The C<catch> block is invoked in a topicalizer context (like a C<given> block),
286 but note that you can't return a useful value from C<catch> using the C<when>
287 blocks without an explicit C<return>.
289 This is somewhat similar to Perl 6's C<CATCH> blocks. You can use it to
290 concisely match errors:
295 when (/^Can't locate .*?\.pm in \@INC/) { } # ignore
305 C<@_> is not available, you need to name your args:
308 my ( $self, @args ) = @_;
309 try { $self->bar(@args) }
314 C<return> returns from the C<try> block, not from the parent sub (note that
315 this is also how C<eval> works, but not how L<TryCatch> works):
318 try { return "foo" };
326 C<try> introduces another caller stack frame. L<Sub::Uplevel> is not used. L<Carp>
327 will report this when using full stack traces. This lack of magic is considered
332 The value of C<$_> in the C<catch> block is not guaranteed to be preserved,
333 there is no safe way to ensure this if C<eval> is used unhygenically in
334 destructors. It's only guaranteed that the C<catch> will be called.
338 The return value of the C<catch> block is not ignored, so if testing the result
339 of the expression for truth on success, be sure to return a false value from
347 return; # avoid returning a true value;
360 Much more feature complete, more convenient semantics, but at the cost of
361 implementation complexity.
365 Automatic error throwing for builtin functions and more. Also designed to
366 work well with C<given>/C<when>.
370 A lightweight role for rolling your own exception classes.
374 Exception object implementation with a C<try> statement. Does not localize
377 =item L<Exception::Class::TryCatch>
379 Provides a C<catch> statement, but properly calling C<eval> is your
382 The C<try> keyword pushes C<$@> onto an error stack, avoiding some of the
383 issues with C<$@>, but you still need to localize to prevent clobbering.
387 =head1 LIGHTNING TALK
389 I gave a lightning talk about this module, you can see the slides (Firefox
392 L<http://nothingmuch.woobling.org/talks/takahashi.xul?data=try_tiny.txt>
396 L<http://nothingmuch.woobling.org/talks/yapc_asia_2009/try_tiny.yml>
398 =head1 VERSION CONTROL
400 L<http://github.com/nothingmuch/try-tiny/>
404 Yuval Kogman E<lt>nothingmuch@woobling.orgE<gt>
408 Copyright (c) 2009 Yuval Kogman. All rights reserved.
409 This program is free software; you can redistribute
410 it and/or modify it under the terms of the MIT license.