Skip to content

Instantly share code, notes, and snippets.

@yowcow
Created March 19, 2013 01:45
Show Gist options
  • Save yowcow/5192987 to your computer and use it in GitHub Desktop.
Save yowcow/5192987 to your computer and use it in GitHub Desktop.
Minimal exception handling
use strict;
use warnings;
use Carp ();
sub try (&@) {
my $try = shift;
my ($catch, @finally);
while (my ($kind, $coderef) = splice @_, 0, 2) {
if ($kind eq 'catch') {
$catch = $coderef;
}
elsif ($kind eq 'finally') {
push @finally, $coderef;
}
else {
Carp::croak '変なCB: '. ref $coderef;
}
}
# try
eval { $try->(); };
# catch
if ($@ && defined $catch) {
local $_ = $@;
$catch->();
}
# finally
$_->() for @finally;
}
sub catch (&@) {
catch => @_;
}
sub finally (&@) {
finally => @_;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment