Exception-Class-TryCatch-1.12/0000755000175000017500000000000011103673576015126 5ustar daviddavidException-Class-TryCatch-1.12/lib/0000755000175000017500000000000011103673576015674 5ustar daviddavidException-Class-TryCatch-1.12/lib/Exception/0000755000175000017500000000000011103673576017632 5ustar daviddavidException-Class-TryCatch-1.12/lib/Exception/Class/0000755000175000017500000000000011103673576020677 5ustar daviddavidException-Class-TryCatch-1.12/lib/Exception/Class/TryCatch.pm0000444000175000017500000002571111103673576022762 0ustar daviddavid# Copyright (c) 2008 by David Golden. All rights reserved. # Licensed under Apache License, Version 2.0 (the "License"). # You may not use this file except in compliance with the License. # A copy of the License was distributed with this file or you may obtain a # copy of the License from http://www.apache.org/licenses/LICENSE-2.0 package Exception::Class::TryCatch; $VERSION = '1.12'; @ISA = qw (Exporter); @EXPORT = qw ( catch try ); @EXPORT_OK = qw ( caught ); use 5.005; # Aiming for same as Exception::Class #use warnings -- not supported in Perl 5.5, darn use strict; use Exception::Class; use Exporter (); my @error_stack; #--------------------------------------------------------------------------# # catch() #--------------------------------------------------------------------------# sub catch(;$$) { my $e; my $err = @error_stack ? pop @error_stack : $@; if ( UNIVERSAL::isa($err, 'Exception::Class::Base' ) ) { $e = $err; } elsif ($err eq '') { $e = undef; } else { # use error message or hope something stringifies $e = Exception::Class::Base->new( "$err" ); } unless ( ref($_[0]) eq 'ARRAY' ) { $_[0] = $e; shift; } if ($e) { if ( defined($_[0]) and ref($_[0]) eq 'ARRAY' ) { $e->rethrow() unless grep { $e->isa($_) } @{$_[0]}; } } return wantarray ? ( $e ? ($e) : () ) : $e; } *caught = \&catch; #--------------------------------------------------------------------------# # try() #--------------------------------------------------------------------------# sub try($) { my $v = shift; push @error_stack, $@; return ref($v) eq 'ARRAY' ? @$v : $v if wantarray; return $v; } 1; __END__ =begin wikidoc = NAME Exception::Class::TryCatch - Syntactic try/catch sugar for use with Exception::Class = VERSION This documentation describes version %%VERSION%%. = SYNOPSIS use Exception::Class::TryCatch; # simple usage of catch() eval { Exception::Class::Base->throw('error') }; catch my $err and warn $err->error; # catching only certain types or else rethrowing eval { Exception::Class::Base::SubClass->throw('error') }; catch( my $err, ['Exception::Class::Base', 'Other::Exception'] ) and warn $err->error; # catching and handling different types of errors eval { Exception::Class::Base->throw('error') }; if ( catch my $err ) { $err->isa('this') and do { handle_this($err) }; $err->isa('that') and do { handle_that($err) }; } # use "try eval" to push exceptions onto a stack to catch later try eval { Exception::Class::Base->throw('error') }; do { # cleanup that might use "try/catch" again }; catch my $err; # catches a matching "try" = DESCRIPTION Exception::Class::TryCatch provides syntactic sugar for use with [Exception::Class] using the familiar keywords {try} and {catch}. Its primary objective is to allow users to avoid dealing directly with {$@} by ensuring that any exceptions caught in an {eval} are captured as [Exception::Class] objects, whether they were thrown objects to begin with or whether the error resulted from {die}. This means that users may immediately use {isa} and various [Exception::Class] methods to process the exception. In addition, this module provides for a method to push errors onto a hidden error stack immediately after an {eval} so that cleanup code or other error handling may also call {eval} without the original error in {$@} being lost. Inspiration for this module is due in part to Dave Rolsky's article "Exception Handling in Perl With Exception::Class" in ~The Perl Journal~ (Rolsky 2004). The {try/catch} syntax used in this module does not use code reference prototypes the way the [Error.pm|Error] module does, but simply provides some helpful functionality when used in combination with {eval}. As a result, it avoids the complexity and dangers involving nested closures and memory leaks inherent in [Error.pm|Error] (Perrin 2003). Rolsky (2004) notes that these memory leaks may not occur in recent versions of Perl, but the approach used in Exception::Class::TryCatch should be safe for all versions of Perl as it leaves all code execution to the {eval} in the current scope, avoiding closures altogether. = USAGE == {catch} # zero argument form my $err = catch; # one argument forms catch my $err; my $err = catch( [ 'Exception::Type', 'Exception::Other::Type' ] ); # two argument form catch my $err, [ 'Exception::Type', 'Exception::Other::Type' ]; Returns an {Exception::Class::Base} object (or an object which is a subclass of it) if an exception has been caught by {eval}. If no exception was thrown, it returns {undef} in scalar context and an empty list in list context. The exception is either popped from a hidden error stack (see {try}) or, if the stack is empty, taken from the current value of {$@}. If the exception is not an {Exception::Class::Base} object (or subclass object), an {Exception::Class::Base} object will be created using the string contents of the exception. This means that calls to {die} will be wrapped and may be treated as exception objects. Other objects caught will be stringfied and wrapped likewise. Such wrapping will likely result in confusing stack traces and the like, so any methods other than {error} used on {Exception::Class::Base} objects caught should be used with caution. {catch} is prototyped to take up to two optional scalar arguments. The single argument form has two variations. * If the argument is a reference to an array, any exception caught that is not of the same type (or a subtype) of one of the classes listed in the array will be rethrown. * If the argument is not a reference to an array, {catch} will set the argument to the same value that is returned. This allows for the {catch my $err} idiom without parentheses. In the two-argument form, the first argument is set to the same value as is returned. The second argument must be an array reference and is handled the same as as for the single argument version with an array reference, as given above. == {caught} (DEPRECATED) {caught} is a synonym for {catch} for syntactic convenience. NOTE: Exception::Class version 1.21 added a "caught" method of its own. It provides somewhat similar functionality to this subroutine, but with very different semantics. As this class is intended to work closely with Exception::Class, the existence of a subroutine and a method with the same name is liable to cause confusion and this method is deprecated and may be removed in future releases of Exception::Class::TryCatch. This method is no longer exported by default. == {try} # void context try eval { # dangerous code }; do { # cleanup code can use try/catch }; catch my $err; # scalar context $rv = try eval { return $scalar }; # list context @rv = try [ eval { return @array } ]; Pushes the current error ({$@}) onto a hidden error stack for later use by {catch}. {try} uses a prototype that expects a single scalar so that it can be used with eval without parentheses. As {eval { BLOCK }} is an argument to try, it will be evaluated just prior to {try}, ensuring that {try} captures the correct error status. {try} does not itself handle any errors -- it merely records the results of {eval}. {try { BLOCK }} will be interpreted as passing a hash reference and will (probably) not compile. (And if it does, it will result in very unexpected behavior.) Since {try} requires a single argument, {eval} will normally be called in scalar context. To use {eval} in list context with {try}, put the call to {eval} in an anonymous array: @rv = try [ eval {return @array} ]; When {try} is called in list context, if the argument to {try} is an array reference, {try} will dereference the array and return the resulting list. In scalar context, {try} passes through the scalar value returned by {eval} without modifications -- even if that is an array reference. $rv = try eval { return $scalar }; $rv = try eval { return [ qw( anonymous array ) ] }; Of course, if the eval throws an exception, {eval} and thus {try} will return undef. {try} must always be properly bracketed with a matching {catch} or unexpected behavior may result when {catch} pops the error off of the stack. {try} executes right after its {eval}, so inconsistent usage of {try} like the following will work as expected: try eval { eval { die "inner" }; catch my $inner_err die "outer" if $inner_err; }; catch my $outer_err; # handle $outer_err; However, the following code is a problem: # BAD EXAMPLE try eval { try eval { die "inner" }; die $@ if $@; }; catch my $outer_err; # handle $outer_err; This code will appear to run correctly, but {catch} gets the exception from the inner {try}, not the outer one, and there will still be an exception on the error stack which will be caught by the next {catch} in the program, causing unexpected (and likely hard to track) behavior. In short, if you use {try}, you must have a matching {catch}. The problem code above should be rewritten as: try eval { try eval { die "inner" }; catch my $inner_err; $inner_err->rethrow if $inner_err; }; catch my $outer_err; # handle $outer_err; = BUGS Please report any bugs or feature using the CPAN Request Tracker. Bugs can be submitted through the web interface at [http://rt.cpan.org/Dist/Display.html?Queue=Exception-Class-TryCatch] When submitting a bug or request, please include a test-file or a patch to an existing test-file that illustrates the bug or desired feature. = REFERENCES 0 perrin. (2003), "Re: Re2: Learning how to use the Error module by example", (perlmonks.org), Available: http://www.perlmonks.org/index.pl?node_id=278900 (Accessed September 8, 2004). 0 Rolsky, D. (2004), "Exception Handling in Perl with Exception::Class", ~The Perl Journal~, vol. 8, no. 7, pp. 9-13 = SEE ALSO * [Exception::Class] * [Error] -- but see (Perrin 2003) before using = AUTHOR David A. Golden (DAGOLDEN) = COPYRIGHT AND LICENSE Copyright (c) 2004-2008 by David A. Golden. All rights reserved. Licensed under Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License was distributed with this file or you may obtain a copy of the License from http://www.apache.org/licenses/LICENSE-2.0 Files produced as output though the use of this software, shall not be considered Derivative Works, but shall be considered the original work of the Licensor. Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =end wikidoc =cut Exception-Class-TryCatch-1.12/lib/Exception/Class/TryCatch.pod0000444000175000017500000002357711103673576023140 0ustar daviddavid# Generated by Pod::WikiDoc version 0.18 =pod =head1 NAME Exception::Class::TryCatch - Syntactic tryEcatch sugar for use with Exception::Class =head1 VERSION This documentation describes version 1.12. =head1 SYNOPSIS use Exception::Class::TryCatch; # simple usage of catch() eval { Exception::Class::Base->throw('error') }; catch my $err and warn $err->error; # catching only certain types or else rethrowing eval { Exception::Class::Base::SubClass->throw('error') }; catch( my $err, ['Exception::Class::Base', 'Other::Exception'] ) and warn $err->error; # catching and handling different types of errors eval { Exception::Class::Base->throw('error') }; if ( catch my $err ) { $err->isa('this') and do { handle_this($err) }; $err->isa('that') and do { handle_that($err) }; } # use "try eval" to push exceptions onto a stack to catch later try eval { Exception::Class::Base->throw('error') }; do { # cleanup that might use "try/catch" again }; catch my $err; # catches a matching "try" =head1 DESCRIPTION Exception::Class::TryCatch provides syntactic sugar for use with L using the familiar keywords C<<< try >>> and C<<< catch >>>. Its primary objective is to allow users to avoid dealing directly with C<<< $@ >>> by ensuring that any exceptions caught in an C<<< eval >>> are captured as L objects, whether they were thrown objects to begin with or whether the error resulted from C<<< die >>>. This means that users may immediately use C<<< isa >>> and various L methods to process the exception. In addition, this module provides for a method to push errors onto a hidden error stack immediately after an C<<< eval >>> so that cleanup code or other error handling may also call C<<< eval >>> without the original error in C<<< $@ >>> being lost. Inspiration for this module is due in part to Dave Rolsky's article "Exception Handling in Perl With Exception::Class" in I (Rolsky 2004). The C<<< try/catch >>> syntax used in this module does not use code reference prototypes the way the L module does, but simply provides some helpful functionality when used in combination with C<<< eval >>>. As a result, it avoids the complexity and dangers involving nested closures and memory leaks inherent in L (Perrin 2003). Rolsky (2004) notes that these memory leaks may not occur in recent versions of Perl, but the approach used in Exception::Class::TryCatch should be safe for all versions of Perl as it leaves all code execution to the C<<< eval >>> in the current scope, avoiding closures altogether. =head1 USAGE =head2 C<<< catch >>> # zero argument form my $err = catch; # one argument forms catch my $err; my $err = catch( [ 'Exception::Type', 'Exception::Other::Type' ] ); # two argument form catch my $err, [ 'Exception::Type', 'Exception::Other::Type' ]; Returns an C<<< Exception::Class::Base >>> object (or an object which is a subclass of it) if an exception has been caught by C<<< eval >>>. If no exception was thrown, it returns C<<< undef >>> in scalar context and an empty list in list context. The exception is either popped from a hidden error stack (see C<<< try >>>) or, if the stack is empty, taken from the current value of C<<< $@ >>>. If the exception is not an C<<< Exception::Class::Base >>> object (or subclass object), an C<<< Exception::Class::Base >>> object will be created using the string contents of the exception. This means that calls to C<<< die >>> will be wrapped and may be treated as exception objects. Other objects caught will be stringfied and wrapped likewise. Such wrapping will likely result in confusing stack traces and the like, so any methods other than C<<< error >>> used on C<<< Exception::Class::Base >>> objects caught should be used with caution. C<<< catch >>> is prototyped to take up to two optional scalar arguments. The single argument form has two variations. =over =item * If the argument is a reference to an array, any exception caught that is not of the same type (or a subtype) of one of the classes listed in the array will be rethrown. =item * If the argument is not a reference to an array, C<<< catch >>> will set the argument to the same value that is returned. This allows for the C<<< catch my $err >>> idiom without parentheses. =back In the two-argument form, the first argument is set to the same value as is returned. The second argument must be an array reference and is handled the same as as for the single argument version with an array reference, as given above. =head2 C<<< caught >>> (DEPRECATED) C<<< caught >>> is a synonym for C<<< catch >>> for syntactic convenience. NOTE: Exception::Class version 1.21 added a "caught" method of its own. It provides somewhat similar functionality to this subroutine, but with very different semantics. As this class is intended to work closely with Exception::Class, the existence of a subroutine and a method with the same name is liable to cause confusion and this method is deprecated and may be removed in future releases of Exception::Class::TryCatch. This method is no longer exported by default. =head2 C<<< try >>> # void context try eval { # dangerous code }; do { # cleanup code can use try/catch }; catch my $err; # scalar context $rv = try eval { return $scalar }; # list context @rv = try [ eval { return @array } ]; Pushes the current error (C<<< $@ >>>) onto a hidden error stack for later use by C<<< catch >>>. C<<< try >>> uses a prototype that expects a single scalar so that it can be used with eval without parentheses. As C<<< eval { BLOCK } >>> is an argument to try, it will be evaluated just prior to C<<< try >>>, ensuring that C<<< try >>> captures the correct error status. C<<< try >>> does not itself handle any errors -- it merely records the results of C<<< eval >>>. C<<< try { BLOCK } >>> will be interpreted as passing a hash reference and will (probably) not compile. (And if it does, it will result in very unexpected behavior.) Since C<<< try >>> requires a single argument, C<<< eval >>> will normally be called in scalar context. To use C<<< eval >>> in list context with C<<< try >>>, put the call to C<<< eval >>> in an anonymous array: @rv = try [ eval {return @array} ]; When C<<< try >>> is called in list context, if the argument to C<<< try >>> is an array reference, C<<< try >>> will dereference the array and return the resulting list. In scalar context, C<<< try >>> passes through the scalar value returned by C<<< eval >>> without modifications -- even if that is an array reference. $rv = try eval { return $scalar }; $rv = try eval { return [ qw( anonymous array ) ] }; Of course, if the eval throws an exception, C<<< eval >>> and thus C<<< try >>> will return undef. C<<< try >>> must always be properly bracketed with a matching C<<< catch >>> or unexpected behavior may result when C<<< catch >>> pops the error off of the stack. C<<< try >>> executes right after its C<<< eval >>>, so inconsistent usage of C<<< try >>> like the following will work as expected: try eval { eval { die "inner" }; catch my $inner_err die "outer" if $inner_err; }; catch my $outer_err; # handle $outer_err; However, the following code is a problem: # BAD EXAMPLE try eval { try eval { die "inner" }; die $@ if $@; }; catch my $outer_err; # handle $outer_err; This code will appear to run correctly, but C<<< catch >>> gets the exception from the inner C<<< try >>>, not the outer one, and there will still be an exception on the error stack which will be caught by the next C<<< catch >>> in the program, causing unexpected (and likely hard to track) behavior. In short, if you use C<<< try >>>, you must have a matching C<<< catch >>>. The problem code above should be rewritten as: try eval { try eval { die "inner" }; catch my $inner_err; $inner_err->rethrow if $inner_err; }; catch my $outer_err; # handle $outer_err; =head1 BUGS Please report any bugs or feature using the CPAN Request Tracker. Bugs can be submitted through the web interface at L When submitting a bug or request, please include a test-file or a patch to an existing test-file that illustrates the bug or desired feature. =head1 REFERENCES =over =item 1. perrin. (2003), "Re: Re2: Learning how to use the Error module by example", (perlmonks.org), Available: http:EEwww.perlmonks.orgEindex.pl?node_id=278900 (Accessed September 8, 2004). =item 2. Rolsky, D. (2004), "Exception Handling in Perl with Exception::Class", I, vol. 8, no. 7, pp. 9-13 =back =head1 SEE ALSO =over =item * L =item * L -- but see (Perrin 2003) before using =back =head1 AUTHOR David A. Golden (DAGOLDEN) =head1 COPYRIGHT AND LICENSE Copyright (c) 2004-2008 by David A. Golden. All rights reserved. Licensed under Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License was distributed with this file or you may obtain a copy of the License from http:EEwww.apache.orgElicensesELICENSE-2.0 Files produced as output though the use of this software, shall not be considered Derivative Works, but shall be considered the original work of the Licensor. Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Exception-Class-TryCatch-1.12/xt/0000755000175000017500000000000011103673576015561 5ustar daviddavidException-Class-TryCatch-1.12/xt/stopwords.txt0000444000175000017500000000007211103673576020363 0ustar daviddavidCPAN CTRL DAGOLDEN Foo MSWin README STDERR STDOUT XS html Exception-Class-TryCatch-1.12/xt/pod-format.t0000444000175000017500000000075311103673576020021 0ustar daviddavid# Copyright (c) 2008 by David Golden. All rights reserved. # Licensed under Apache License, Version 2.0 (the "License"). # You may not use this file except in compliance with the License. # A copy of the License was distributed with this file or you may obtain a # copy of the License from http://www.apache.org/licenses/LICENSE-2.0 use Test::More; my $min_tp = 1.22; eval "use Test::Pod $min_tp"; plan skip_all => "Test::Pod $min_tp required for testing POD" if $@; all_pod_files_ok(); Exception-Class-TryCatch-1.12/xt/spelling.t0000444000175000017500000000135311103673576017563 0ustar daviddavid# Copyright (c) 2008 by David Golden. All rights reserved. # Licensed under Apache License, Version 2.0 (the "License"). # You may not use this file except in compliance with the License. # A copy of the License was distributed with this file or you may obtain a # copy of the License from http://www.apache.org/licenses/LICENSE-2.0 use Test::More; use IO::File; my $min_tps = 0.11; eval "use Test::Spelling $min_tps"; plan skip_all => "Test::Spelling $min_tps required for testing POD" if $@; system( "ispell -v" ) and plan skip_all => "No ispell"; set_spell_cmd( "ispell -l" ); my $swf = IO::File->new('xt/stopwords.txt'); my @stopwords = grep { length } map { chomp; $_ } <$swf>; add_stopwords( @stopwords ); all_pod_files_spelling_ok(); Exception-Class-TryCatch-1.12/xt/critic.t0000444000175000017500000000107011103673576017217 0ustar daviddavid# Copyright (c) 2008 by David Golden. All rights reserved. # Licensed under Apache License, Version 2.0 (the "License"). # You may not use this file except in compliance with the License. # A copy of the License was distributed with this file or you may obtain a # copy of the License from http://www.apache.org/licenses/LICENSE-2.0 use strict; use warnings; use File::Spec; use Test::More; require Test::Perl::Critic; my $rcfile = File::Spec->catfile( 'xt', 'perlcriticrc' ); Test::Perl::Critic->import( -profile => $rcfile ); all_critic_ok( 'lib', 'examples' ); Exception-Class-TryCatch-1.12/xt/perlcriticrc0000444000175000017500000000100711103673576020165 0ustar daviddavidseverity = 5 verbose = 8 [Variables::ProhibitPunctuationVars] allow = $@ $! # Turn these off [-BuiltinFunctions::ProhibitStringyEval] [-ControlStructures::ProhibitPostfixControls] [-ControlStructures::ProhibitUnlessBlocks] [-Documentation::RequirePodSections] [-InputOutput::ProhibitInteractiveTest] [-Miscellanea::RequireRcsKeywords] [-References::ProhibitDoubleSigils] [-RegularExpressions::RequireExtendedFormatting] [-InputOutput::ProhibitTwoArgOpen] # Turn this on [Lax::ProhibitStringyEval::ExceptForRequire] Exception-Class-TryCatch-1.12/xt/pod-coverage.t0000444000175000017500000000160411103673576020320 0ustar daviddavid# Copyright (c) 2008 by David Golden. All rights reserved. # Licensed under Apache License, Version 2.0 (the "License"). # You may not use this file except in compliance with the License. # A copy of the License was distributed with this file or you may obtain a # copy of the License from http://www.apache.org/licenses/LICENSE-2.0 use Test::More; my $min_tpc = 1.08; eval "use Test::Pod::Coverage $min_tpc"; plan skip_all => "Test::Pod::Coverage $min_tpc required for testing POD coverage" if $@; my $min_pc = 0.17; eval "use Pod::Coverage $min_pc"; plan skip_all => "Pod::Coverage $min_pc required for testing POD coverage" if $@; my @modules = all_modules('lib'); plan tests => scalar @modules; for my $mod ( @modules ) { my $doc = "lib/$mod"; $doc =~ s{::}{/}g; $doc = -f "$doc\.pod" ? "$doc\.pod" : "$doc\.pm" ; pod_coverage_ok( $mod, { pod_from => $doc } ); } Exception-Class-TryCatch-1.12/Changes0000444000175000017500000000431011103673576016415 0ustar daviddavidRevision history for Perl module Exception::Class::TryCatch 1.12 Mon Nov 3 17:12:19 EST 2008 - Changed: if no exception was thrown, catch() returns an empty array in list context 1.11 Tue Sep 30 12:21:56 EDT 2008 - Fixed: Exception::Class objects that stringified to an empty string weren't being caught (Alessandro Ranellucci) - Changed: now licensed under the Apache License, version 2.0; (it's clearer, relicensable, and is explicit about contributions) 1.10 Tue Feb 7 21:26:27 EST 2006 - Removed Test::Exception dependency entirely - Downgraded Test::More dependency to 0.45 1.09 Tue Aug 16 10:32:15 EDT 2005 - [RT #14025] updated documentation for try to reflect new calling syntax - deprecated "caught()" as Exception::Class 1.21 added "caught()" with different semantics - updated Test::Exception dependency to 0.21 as 0.20 had build_requires problems of its own 1.08 Mon Aug 1 09:29:00 EDT 2005 - moved build_requires to requires for CPANPLUS bug workaround 1.07 Fri Jun 10 11:30:02 EDT 2005 - reduced Test::More required version to 0.47 1.06 Wed Jun 8 12:02:24 EDT 2005 - removed pod/coverage tests to minimize dependencies for Activestate 1.05 Tue Jun 7 17:34:32 EDT 2005 - updated Build.PL to include build dependencies 1.04 Mon May 16 23:20:23 EDT 2005 - changed Module::Build makefile support to 'traditional' (Perrin) 1.03 Sat Apr 23 09:03:00 EDT 2005 - catch rethrows if optional list of class types isn't matched - added support for both one- and two-arguments forms of catch 1.02 Wed Mar 9 06:47:58 EST 2005 - added pod and pod coverage tests 1.01 Mon Jan 24 22:51:43 EST 2005 - changed "try" to return whatever eval returns - try in list context dereferences an array_ref allowing eval to be called in list context by wrapping in an anonymous array - updated build configuration 1.00 Wed Dec 8 16:28:37 EST 2004 - renamed to Exception::Class::TryCatch (on advice of Dave Rolsky) - minor pod edits 0.10 Thu Sep 9 10:20:51 EDT 2004 - initial public release as Exception::Class::Sugar 0.01 Fri Sep 3 00:09:17 2004 - original version; created by ExtUtils::ModuleMaker::TT Exception-Class-TryCatch-1.12/MANIFEST0000444000175000017500000000046311103673576016260 0ustar daviddavidBuild.PL Changes inc/Module/Build/WikiDoc.pm INSTALL lib/Exception/Class/TryCatch.pm lib/Exception/Class/TryCatch.pod LICENSE MANIFEST MANIFEST.SKIP README t/01_Exception_Class_TryCatch.t Todo xt/critic.t xt/perlcriticrc xt/pod-coverage.t xt/pod-format.t xt/spelling.t xt/stopwords.txt Makefile.PL META.yml Exception-Class-TryCatch-1.12/t/0000755000175000017500000000000011103673576015371 5ustar daviddavidException-Class-TryCatch-1.12/t/01_Exception_Class_TryCatch.t0000444000175000017500000001700611103673576022744 0ustar daviddavid# Exception::Class::TryCatch use strict; use Test::More tests => 45 ; use Exception::Class::TryCatch qw( try catch caught ); use Exception::Class 'My::Exception::Class', 'My::Other::Exception'; package My::Exception::Class; # check for bug when some Exception class stringifies to empty string use overload q{""} => sub { return '' }, fallback => 1 ; package main; my $e; #--------------------------------------------------------------------------# # Test basic catching of Exception::Class thrown errors #--------------------------------------------------------------------------# eval { My::Exception::Class->throw('error1') }; $e = catch; ok ( $e, "Caught My::Exception::Class error1" ); isa_ok ( $e, 'Exception::Class::Base' ); isa_ok ( $e, 'My::Exception::Class' ); is ( $e->error, 'error1', "Exception is 'error1'" ); eval { My::Exception::Class->throw('error2'); }; $e = catch; ok ( $e, "Caught My::Exception::Class error2" ); isa_ok ( $e, 'My::Exception::Class' ); is ( $e->error, 'error2', "Exception is 'error2'" ); #--------------------------------------------------------------------------# # Test handling of normal die (not Exception::Class throw() ) #--------------------------------------------------------------------------# eval { die "error3" }; $e = catch; ok ( $e, "Caught 'die error3'" ); isa_ok ( $e, 'Exception::Class::Base' ); like ( $e->error, qr/^error3 at/, "Exception is 'error3 at...'" ); eval { die 0 }; $e = catch; ok ( $e, "Caught 'die 0'" ); isa_ok ( $e, 'Exception::Class::Base' ); like ( $e->error, qr/^0 at/, "Exception is '0 at...'" ); eval { die }; $e = catch; ok ( $e, "Caught 'die'" ); isa_ok ( $e, 'Exception::Class::Base' ); like ( $e->error, qr/^Died at/, "Exception is 'Died at...'" ); #--------------------------------------------------------------------------# # Test handling of non-dying evals #--------------------------------------------------------------------------# eval { 1 }; $e = catch; is ($e, undef, "Didn't catch eval of 1" ); eval { 0 }; $e = catch; is ($e, undef, "Didn't catch eval of 0" ); #--------------------------------------------------------------------------# # Test catch (my e) syntax-- pass by reference #--------------------------------------------------------------------------# eval { My::Exception::Class->throw('error'); }; catch my $err; is ( $err->error, 'error', "catch X syntax worked" ); #--------------------------------------------------------------------------# # Test caught synonym #--------------------------------------------------------------------------# undef $err; eval { My::Exception::Class->throw( "error" ) }; caught $err; is ( $err->error, 'error', "caught synonym worked" ); #--------------------------------------------------------------------------# # Test catch setting error variable to undef if no error #--------------------------------------------------------------------------# eval { My::Exception::Class->throw( "error" ) }; catch $err; eval { 1 }; catch $err; is ( $err, undef, "catch undefs a passed error variable if no error" ); #--------------------------------------------------------------------------# # Test try passing through results of eval #--------------------------------------------------------------------------# my $test_val = 23; my @test_vals = ( 1, 2, 3 ); my $rv = try eval { return $test_val }; is( $rv, $test_val, "try in scalar context passes through result of eval" ); $rv = try eval { return \@test_vals }; is( $rv, \@test_vals, "try in scalar context passes an array ref as is" ); my @rv = try [ eval { return @test_vals } ]; is_deeply( \@rv, \@test_vals, "try in list context dereferences an array ref passed to it" ); @rv = try eval { return $test_val }; is_deeply( \@rv, [ $test_val ], "try in list context passes through a scalar return" ); #--------------------------------------------------------------------------# # Test simple try/catch #--------------------------------------------------------------------------# $rv = try eval { My::Exception::Class->throw( "error" ) }; catch $err; is ( $rv, undef, "try gets undef on exception" ); is ( $err->error, 'error', "simple try/catch works" ); #--------------------------------------------------------------------------# # Test try/catch to array #--------------------------------------------------------------------------# $rv = try eval { My::Exception::Class->throw( "error" ) }; my @err = catch; is ( scalar @err, 1, '@array = catch' ); is ( $err[0]->error, 'error', 'array catch works' ); #--------------------------------------------------------------------------# # Test try/catch to array -- no error #--------------------------------------------------------------------------# $rv = try eval { 42 }; @err = catch; is ( scalar @err, 0, 'array catch with no error returns empty array' ); #--------------------------------------------------------------------------# # Test multiple try/catch with double error #--------------------------------------------------------------------------# my $inner_err; my $outer_err; for my $out ( 0, 1 ) { for my $in (0, 1 ) { try eval { $out ? My::Exception::Class->throw( "outer" ) : 1 }; try eval { $in ? My::Exception::Class->throw( "inner" ) : 1}; catch $inner_err; catch $outer_err; if ($in) { is ( $inner_err->error, "inner", "Inner try caught correctly in case ($out,$in)" ); } else { is ( $inner_err, undef, "Inner try caught correctly in case ($out,$in)" ); } if ($out) { is ( $outer_err->error, "outer", "Outer try caught correctly in case ($out,$in)" ); } else { is ( $outer_err, undef, "Outer try caught correctly in case ($out,$in)" ); } } } #--------------------------------------------------------------------------# # Test catch rethrowing unless a list is matched -- one argument version #--------------------------------------------------------------------------# { try eval { try eval { My::Exception::Class->throw( "error" ) }; $err = catch( ['My::Other::Exception'] ); diag( "Shouldn't be here because \$err is a " . ref($err) . " not a My::Other::Exception." ); }; catch $outer_err; } ok( UNIVERSAL::isa($outer_err, 'My::Exception::Class'), "catch not matching list should rethrow -- single arg version"); eval { eval { My::Exception::Class->throw( "error" ) }; $err = catch( ['My::Exception::Class'] ); }; is( $@, q{}, "catch matching list lives -- single arg version"); eval { 1 }; $e = catch ['My::Exception::Class']; is ( $e, undef, "catch returns undef if no error -- single arg version" ); #--------------------------------------------------------------------------# # Test catch rethrowing unless a list is matched -- two argument version #--------------------------------------------------------------------------# { try eval { try eval { My::Exception::Class->throw( "error" ) }; catch( $err, ['My::Other::Exception'] ); diag( "Shouldn't be here unless " . ref($err) . " is a My::Other::Exception." ); }; catch $outer_err; } ok( UNIVERSAL::isa($outer_err, 'My::Exception::Class'), "catch not matching list should rethrow -- two arg version"); eval { eval { My::Exception::Class->throw( "error" ) }; catch( $err, ['My::Exception::Class'] ); }; is( $@, q{}, "catch matching list lives -- two arg version" ); eval { 1 }; $e = catch $err, ['My::Exception::Class']; is ( $e, undef, "catch returns undef if no error -- two arg version" ); is ( $err, undef, "catch undefs a passed error variable if no error -- two arg version"); Exception-Class-TryCatch-1.12/MANIFEST.SKIP0000444000175000017500000000117511103673576017026 0ustar daviddavid# Copyright (c) 2008 by David Golden. All rights reserved. # Licensed under Apache License, Version 2.0 (the "License"). # You may not use this file except in compliance with the License. # A copy of the License was distributed with this file or you may obtain a # copy of the License from http://www.apache.org/licenses/LICENSE-2.0 # Version control files and dirs. \bRCS\b \bCVS\b ,v$ .svn/ ^.git # Generated by Perl module toolchain ^MANIFEST\.(?!SKIP) ^Makefile$ ^blib/ ^blibdirs$ ^PM_to_blib$ ^MakeMaker-\d ^Build$ ^_build ^cover_db ^.*\.bat$ # Temp, old, vi and emacs files. ~$ \.old$ \#\.*\#$ \.\#$ \.swp$ \.bak$ ^pod.*\.tmp$ Exception-Class-TryCatch-1.12/META.yml0000444000175000017500000000114411103673576016375 0ustar daviddavid--- name: Exception-Class-TryCatch version: 1.12 author: - 'David Golden ' abstract: Syntactic tryEcatch sugar for use with Exception::Class license: apache resources: license: http://apache.org/licenses/LICENSE-2.0 requires: Exception::Class: 1.2 perl: 5.005 build_requires: Test::More: 0.47 provides: Exception::Class::TryCatch: file: lib/Exception/Class/TryCatch.pm version: 1.12 generated_by: Module::Build version 0.3 meta-spec: url: http://module-build.sourceforge.net/META-spec-v1.2.html version: 1.2 no_index: directory: - examples - inc - t Exception-Class-TryCatch-1.12/Todo0000444000175000017500000000064711103673576015763 0ustar daviddavid# Copyright (c) 2008 by David Golden. All rights reserved. # Licensed under Apache License, Version 2.0 (the "License"). # You may not use this file except in compliance with the License. # A copy of the License was distributed with this file or you may obtain a # copy of the License from http://www.apache.org/licenses/LICENSE-2.0 - Write some code - Write some tests - Replace boilerplate docs with real documentation Exception-Class-TryCatch-1.12/inc/0000755000175000017500000000000011103673576015677 5ustar daviddavidException-Class-TryCatch-1.12/inc/Module/0000755000175000017500000000000011103673576017124 5ustar daviddavidException-Class-TryCatch-1.12/inc/Module/Build/0000755000175000017500000000000011103673576020163 5ustar daviddavidException-Class-TryCatch-1.12/inc/Module/Build/WikiDoc.pm0000444000175000017500000000323011103673576022046 0ustar daviddavid# Copyright (c) 2008 by David Golden. All rights reserved. # Licensed under Apache License, Version 2.0 (the "License"). # You may not use this file except in compliance with the License. # A copy of the License was distributed with this file or you may obtain a # copy of the License from http://www.apache.org/licenses/LICENSE-2.0 package Module::Build::WikiDoc; use strict; use base qw/Module::Build/; use File::Spec; sub ACTION_wikidoc { my $self = shift; eval "use Pod::WikiDoc"; if ( $@ eq '' ) { my $parser = Pod::WikiDoc->new({ comment_blocks => 1, keywords => { VERSION => $self->dist_version }, }); for my $src ( keys %{ $self->find_pm_files() } ) { (my $tgt = $src) =~ s{\.pm$}{.pod}; $parser->filter( { input => $src, output => $tgt, }); print "Creating $tgt\n"; $tgt =~ s{\\}{/}g; $self->_add_to_manifest( 'MANIFEST', $tgt ); } } else { warn "Pod::WikiDoc not available. Skipping wikidoc.\n"; } } sub ACTION_test { my $self = shift; my $missing_pod; for my $src ( keys %{ $self->find_pm_files() } ) { (my $tgt = $src) =~ s{\.pm$}{.pod}; $missing_pod = 1 if ! -e $tgt; } if ( $missing_pod ) { $self->depends_on('wikidoc'); $self->depends_on('build'); } $self->SUPER::ACTION_test; } sub ACTION_testpod { my $self = shift; $self->depends_on('wikidoc'); $self->SUPER::ACTION_testpod; } sub ACTION_distmeta { my $self = shift; $self->depends_on('wikidoc'); $self->SUPER::ACTION_distmeta; } 1; Exception-Class-TryCatch-1.12/INSTALL0000444000175000017500000000133111103673576016153 0ustar daviddavid# Copyright (c) 2008 by David Golden. All rights reserved. # Licensed under Apache License, Version 2.0 (the "License"). # You may not use this file except in compliance with the License. # A copy of the License was distributed with this file or you may obtain a # copy of the License from http://www.apache.org/licenses/LICENSE-2.0 INSTALLATION This distribution may be installed via one of the following methods: 1. If Build.PL exists and Module::Build is installed: perl Build.PL perl Build perl Build test perl Build install 2. If Makefile.PL exists: perl Makefile.PL make make test make install If you are on a Windows machine you should use 'nmake' or 'dmake' rather than 'make'. Exception-Class-TryCatch-1.12/Makefile.PL0000444000175000017500000000077411103673576017106 0ustar daviddavid# Note: this file was auto-generated by Module::Build::Compat version 0.30 require 5.005; use ExtUtils::MakeMaker; WriteMakefile ( 'PL_FILES' => {}, 'INSTALLDIRS' => 'site', 'NAME' => 'Exception::Class::TryCatch', 'EXE_FILES' => [], 'VERSION_FROM' => 'lib/Exception/Class/TryCatch.pm', 'PREREQ_PM' => { 'Test::More' => '0.47', 'Exception::Class' => '1.2' } ) ; Exception-Class-TryCatch-1.12/LICENSE0000444000175000017500000002613511103673576016140 0ustar daviddavid Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Exception-Class-TryCatch-1.12/Build.PL0000444000175000017500000000200011103673576016410 0ustar daviddavid# Copyright (c) 2008 by David Golden. All rights reserved. # Licensed under Apache License, Version 2.0 (the "License"). # You may not use this file except in compliance with the License. # A copy of the License was distributed with this file or you may obtain a # copy of the License from http://www.apache.org/licenses/LICENSE-2.0 use 5.006; use strict; use warnings; use lib 'inc'; eval "require Pod::WikiDoc"; my $class = $@ ? "Module::Build" : "Module::Build::WikiDoc"; eval "require $class"; my $build = $class->new( module_name => 'Exception::Class::TryCatch', dist_author => 'David Golden ', license => 'apache', create_readme => 1, create_makefile_pl => 'traditional', requires => { 'perl' => '5.005', 'Exception::Class' => 1.20, }, build_requires => { 'Test::More' => 0.47, }, meta_add => { no_index => { directory => [ qw/ examples inc t /], } }, ); $build->create_build_script; Exception-Class-TryCatch-1.12/README0000444000175000017500000002355511103673576016016 0ustar daviddavidNAME Exception::Class::TryCatch - Syntactic try/catch sugar for use with Exception::Class VERSION This documentation describes version 1.12. SYNOPSIS use Exception::Class::TryCatch; # simple usage of catch() eval { Exception::Class::Base->throw('error') }; catch my $err and warn $err->error; # catching only certain types or else rethrowing eval { Exception::Class::Base::SubClass->throw('error') }; catch( my $err, ['Exception::Class::Base', 'Other::Exception'] ) and warn $err->error; # catching and handling different types of errors eval { Exception::Class::Base->throw('error') }; if ( catch my $err ) { $err->isa('this') and do { handle_this($err) }; $err->isa('that') and do { handle_that($err) }; } # use "try eval" to push exceptions onto a stack to catch later try eval { Exception::Class::Base->throw('error') }; do { # cleanup that might use "try/catch" again }; catch my $err; # catches a matching "try" DESCRIPTION Exception::Class::TryCatch provides syntactic sugar for use with Exception::Class using the familiar keywords "try" and "catch". Its primary objective is to allow users to avoid dealing directly with $@ by ensuring that any exceptions caught in an "eval" are captured as Exception::Class objects, whether they were thrown objects to begin with or whether the error resulted from "die". This means that users may immediately use "isa" and various Exception::Class methods to process the exception. In addition, this module provides for a method to push errors onto a hidden error stack immediately after an "eval" so that cleanup code or other error handling may also call "eval" without the original error in $@ being lost. Inspiration for this module is due in part to Dave Rolsky's article "Exception Handling in Perl With Exception::Class" in *The Perl Journal* (Rolsky 2004). The "try/catch" syntax used in this module does not use code reference prototypes the way the Error.pm module does, but simply provides some helpful functionality when used in combination with "eval". As a result, it avoids the complexity and dangers involving nested closures and memory leaks inherent in Error.pm (Perrin 2003). Rolsky (2004) notes that these memory leaks may not occur in recent versions of Perl, but the approach used in Exception::Class::TryCatch should be safe for all versions of Perl as it leaves all code execution to the "eval" in the current scope, avoiding closures altogether. USAGE "catch" # zero argument form my $err = catch; # one argument forms catch my $err; my $err = catch( [ 'Exception::Type', 'Exception::Other::Type' ] ); # two argument form catch my $err, [ 'Exception::Type', 'Exception::Other::Type' ]; Returns an "Exception::Class::Base" object (or an object which is a subclass of it) if an exception has been caught by "eval". If no exception was thrown, it returns "undef" in scalar context and an empty list in list context. The exception is either popped from a hidden error stack (see "try") or, if the stack is empty, taken from the current value of $@. If the exception is not an "Exception::Class::Base" object (or subclass object), an "Exception::Class::Base" object will be created using the string contents of the exception. This means that calls to "die" will be wrapped and may be treated as exception objects. Other objects caught will be stringfied and wrapped likewise. Such wrapping will likely result in confusing stack traces and the like, so any methods other than "error" used on "Exception::Class::Base" objects caught should be used with caution. "catch" is prototyped to take up to two optional scalar arguments. The single argument form has two variations. * If the argument is a reference to an array, any exception caught that is not of the same type (or a subtype) of one of the classes listed in the array will be rethrown. * If the argument is not a reference to an array, "catch" will set the argument to the same value that is returned. This allows for the "catch my $err" idiom without parentheses. In the two-argument form, the first argument is set to the same value as is returned. The second argument must be an array reference and is handled the same as as for the single argument version with an array reference, as given above. "caught" (DEPRECATED) "caught" is a synonym for "catch" for syntactic convenience. NOTE: Exception::Class version 1.21 added a "caught" method of its own. It provides somewhat similar functionality to this subroutine, but with very different semantics. As this class is intended to work closely with Exception::Class, the existence of a subroutine and a method with the same name is liable to cause confusion and this method is deprecated and may be removed in future releases of Exception::Class::TryCatch. This method is no longer exported by default. "try" # void context try eval { # dangerous code }; do { # cleanup code can use try/catch }; catch my $err; # scalar context $rv = try eval { return $scalar }; # list context @rv = try [ eval { return @array } ]; Pushes the current error ($@) onto a hidden error stack for later use by "catch". "try" uses a prototype that expects a single scalar so that it can be used with eval without parentheses. As "eval { BLOCK }" is an argument to try, it will be evaluated just prior to "try", ensuring that "try" captures the correct error status. "try" does not itself handle any errors -- it merely records the results of "eval". "try { BLOCK }" will be interpreted as passing a hash reference and will (probably) not compile. (And if it does, it will result in very unexpected behavior.) Since "try" requires a single argument, "eval" will normally be called in scalar context. To use "eval" in list context with "try", put the call to "eval" in an anonymous array: @rv = try [ eval {return @array} ]; When "try" is called in list context, if the argument to "try" is an array reference, "try" will dereference the array and return the resulting list. In scalar context, "try" passes through the scalar value returned by "eval" without modifications -- even if that is an array reference. $rv = try eval { return $scalar }; $rv = try eval { return [ qw( anonymous array ) ] }; Of course, if the eval throws an exception, "eval" and thus "try" will return undef. "try" must always be properly bracketed with a matching "catch" or unexpected behavior may result when "catch" pops the error off of the stack. "try" executes right after its "eval", so inconsistent usage of "try" like the following will work as expected: try eval { eval { die "inner" }; catch my $inner_err die "outer" if $inner_err; }; catch my $outer_err; # handle $outer_err; However, the following code is a problem: # BAD EXAMPLE try eval { try eval { die "inner" }; die $@ if $@; }; catch my $outer_err; # handle $outer_err; This code will appear to run correctly, but "catch" gets the exception from the inner "try", not the outer one, and there will still be an exception on the error stack which will be caught by the next "catch" in the program, causing unexpected (and likely hard to track) behavior. In short, if you use "try", you must have a matching "catch". The problem code above should be rewritten as: try eval { try eval { die "inner" }; catch my $inner_err; $inner_err->rethrow if $inner_err; }; catch my $outer_err; # handle $outer_err; BUGS Please report any bugs or feature using the CPAN Request Tracker. Bugs can be submitted through the web interface at When submitting a bug or request, please include a test-file or a patch to an existing test-file that illustrates the bug or desired feature. REFERENCES 1. perrin. (2003), "Re: Re2: Learning how to use the Error module by example", (perlmonks.org), Available: http://www.perlmonks.org/index.pl?node_id=278900 (Accessed September 8, 2004). 2. Rolsky, D. (2004), "Exception Handling in Perl with Exception::Class", *The Perl Journal*, vol. 8, no. 7, pp. 9-13 SEE ALSO * Exception::Class * Error -- but see (Perrin 2003) before using AUTHOR David A. Golden (DAGOLDEN) COPYRIGHT AND LICENSE Copyright (c) 2004-2008 by David A. Golden. All rights reserved. Licensed under Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License was distributed with this file or you may obtain a copy of the License from http://www.apache.org/licenses/LICENSE-2.0 Files produced as output though the use of this software, shall not be considered Derivative Works, but shall be considered the original work of the Licensor. Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.