Stupid Moose Tricks: Being Your Own Exception Class

I discovered (by accident) that in Moose you can be your own exception class:

package Local::Iam::MyOwn::Exception;

use Moose;
with 'Throwable';

sub ork {
my ($self, $cow) = @_;

if ($cow ne 'cow') {
$self->throw("Need a 'cow', here!");
}

return ('ork', 'ork', 'ork');
}


package main;

my $lime = Local::Iam::MyOwn::Exception->new();

print join(' .. ', $lime->ork('cow')) . "\n";

print join(' .. ', $lime->ork('horse')) . "\n";

If you run this, you will get output confirming that the class is both a worker (or at least a cow-orker) and an exception:

ork .. ork .. ork
throw called on Throwable object with arguments at /usr/lib/perl5/site_perl/5.14/Throwable.pm line 33.
        Throwable::throw(Local::Iam::MyOwn::Exception=HASH(0x8006c118), "Need a 'cow', here!") called at x.pl line 9
        Local::Iam::MyOwn::Exception::ork(Local::Iam::MyOwn::Exception=HASH(0x8006c118), "horse") called at x.pl line 23

Writing a class that is its own exception means not writing a separate exception class, which might save you (a little) time.

(And remember -- you can 'ork' a cow, but you cannot 'ork' a horse. This code proves it.)

1 Comment

There's nothing Moose specific here. Any package can be used to throw exceptions. Look ma! Strict exceptions!

  use strict;
  package strict {
    use overload q[""] => sub { $_[0][0] };
    sub throw { my $c = shift; die(bless \@_, $c) }
  }
  
  strict->throw("not strict enough!");

(Stack traces are left as an exercise for the reader.)

If you want to save time writing exception classes, I recommend looking at Throwable::Factory instead.

Leave a comment

About Mark Leighton Fisher

user-pic Perl/CPAN user since 1992.