日向夏特殊応援部隊

俺様向けメモ

Error.pm

挙動確かめる用。ちなみに Exception::Class だと pacakge をわざわざ明示的に割り当てる必要は無い。

#!/usr/bin/perl

package ThrowableProcess::Exception;

use base qw(Error::Simple);

package ThrowableProcess::FirstException;

use base qw(ThrowableProcess::Exception);

package ThrowableProcess::SecondException;

use base qw(ThrowableProcess::Exception);

package ThrowableProcess;

use strict;
use warnings;

use Carp::Clan;
use Error qw(:try);

sub do_something {
    my ($class, $is_first, $is_second) = @_;
    $is_first = 0 unless (defined $is_first && $is_first);

    if ($is_first) {
        throw ThrowableProcess::FirstException 'first exception!!!';
    }
    elsif ($is_second) {
        throw ThrowableProcess::SecondException 'second exception!!!';
    }
    else {
        croak 'normal croaking';
    }
}

package main;

use Carp;
use Error qw(:try);
use Perl6::Say;

my @cases = (
    [ 1, 0 ],
    [ 0, 1 ],
    [ 0, 0 ],
);

for my $case (@cases) {
    my ($is_first, $is_second) = @$case;
    try {
        ThrowableProcess->do_something($is_first, $is_second);
    }
    catch ThrowableProcess::FirstException with {
        my $e = shift;
        say $e->text;
    }
    catch ThrowableProcess::SecondException with {
        my $e = shift;
        say $e->text;
    }
    otherwise {
        my $e = shift;
        croak $e;
    }
    finally {
        say "finally";
    };
}

throw とか catch とかは Klass->methodmethod Klass と同様で、しかもそれらがチェインしてますので、途中で ";" とか入れちゃ駄目。