Skip to content

Instantly share code, notes, and snippets.

@koorchik
Created May 19, 2012 07:58
Show Gist options
  • Select an option

  • Save koorchik/2729988 to your computer and use it in GitHub Desktop.

Select an option

Save koorchik/2729988 to your computer and use it in GitHub Desktop.
Try::Tiny dispatch exceptions
package Exception::Base;
use overload
'~~' => sub { $_[0]->isa( $_[1] ) },
fallback => 1;
package Exception1;
use base 'Exception::Base';
sub new { bless {}, shift }
package Exception2;
use base 'Exception::Base';
sub new { bless {}, shift }
package Exception3;
use base 'Exception::Base';
sub new { bless {}, shift }
package main;
use Try::Tiny;
use v5.10;
test_exception( Exception1->new() );
test_exception( Exception2->new() );
test_exception( Exception3->new() );
test_exception("Special text\n");
test_exception("Text exception\n");
sub test_exception {
my $e = shift;
try {
die $e;
}
catch {
when ('Exception1') {
say ref($_) . " matches Exception1";
}
when ('Exception2') {
say ref($_) . " matches Exception2";
}
when ('Exception::Base') {
say ref($_) . " matches Exception::Base";
}
when (/Special/) {
chomp;
say qq{"$_" matches qr/Special/};
}
default {
chomp;
say qq{"$_" matches default};
}
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment