Skip to content

Instantly share code, notes, and snippets.

@yappo
Created February 15, 2013 05:29
Show Gist options
  • Save yappo/4958713 to your computer and use it in GitHub Desktop.
Save yappo/4958713 to your computer and use it in GitHub Desktop.
use strict;
use warnings;
sub try (&;@) {
my($cb, @catches) = @_;
local $@;
my $wantarray = wantarray;
my @ret;
if ($wantarray) {
@ret = eval { $cb->() };
} elsif ( defined $wantarray ) {
$ret[0] = eval { $cb->() };
} else {
eval { $cb->() };
};
my $e = $@;
return @ret unless defined $e;
for (my $i = 0;$i < @catches;$i += 2) {
if (UNIVERSAL::isa($e, $catches[$i])) {
local $_ = $e;
$catches[$i + 1]->();
return;
}
}
die $e;
}
package MyEx {
use parent 'Exception::Tiny';
}
package YourEx {
use parent 'Exception::Tiny';
}
try {
MyEx->throw;
}
'MyEx' => sub { warn },
'YourEx' => sub { warn };
try {
YourEx->throw;
}
'MyEx' => sub { warn },
'YourEx' => sub { warn };
try {
die 'gerry';
}
'MyEx' => sub { warn },
'YourEx' => sub { warn };
__END__
MyEx at ./Try.pl line 39. at ./Try.pl line 41.
YourEx at ./Try.pl line 45. at ./Try.pl line 48.
gerry at ./Try.pl line 51.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment