Exception::Class - A module that allows you to declare real exception classes in Perl


NAME

Exception::Class - A module that allows you to declare real exception classes in Perl


SYNOPSIS

  use Exception::Class
      ( 'MyException',
        'AnotherException' =>
        { isa => 'MyException' },
        'YetAnotherException' =>
        { isa => 'AnotherException',
          description => 'These exceptions are related to IPC' },
        'ExceptionWithFields' =>
        { isa => 'YetAnotherException',
          fields => [ 'grandiosity', 'quixotic' ],
          alias => 'throw_fields',
      );
  # try
  eval { MyException->throw( error => 'I feel funny.'; };
  # catch
  if ( UNIVERSAL::isa( $@, 'MyException' ) )
  {
     warn $@->error, "\n, $@->trace->as_string, "\n";
     warn join ' ',  $@->euid, $@->egid, $@->uid, $@->gid, $@->pid, $@->time;
     exit;
  }
  elsif ( UNIVERSAL::isa( $@, 'ExceptionWithFields' ) )
  {
     $@->quixotic ? do_something_wacky() : do_something_sane();
  }
  else
  {
     ref $@ ? $@->rethrow : die $@;
  }
  # use an alias - without parens subroutine name is checked at
  # compile time
  throw_fields error => "No strawberry", grandiosity => "quite a bit";


DESCRIPTION

Exception::Class allows you to declare exception hierarchies in your modules in a ``Java-esque'' manner.

It features a simple interface allowing programmers to 'declare' exception classes at compile time. It also has a base exception class, Exception::Class::Base, that can be easily extended.

It is designed to make structured exception handling simpler and better by encouraging people to use hierarchies of exceptions in their applications, as opposed to a single catch-all exception class.

This module does not implement any try/catch syntax. Please see the ``OTHER EXCEPTION MODULES (try/catch syntax)'' section for more information on how to get this syntax.


DECLARING EXCEPTION CLASSES

Importing Exception::Class allows you to automagically create Exception::Class::Base subclasses. You can also create subclasses via the traditional means of defining your own subclass with @ISA. These two methods may be easily combined, so that you could subclass an exception class defined via the automagic import, if you desired this.

The syntax for the magic declarations is as follows:

'MANDATORY CLASS NAME' => \%optional_hashref

The hashref may contain the following options:

The Exception::Class magic attempts to detect circular class hierarchies and will die if it finds one. It also detects missing links in a chain, for example if you declare Bar to be a subclass of Foo and never declare Foo.


Exception::Class::Base CLASS METHODS


Exception::Class::Base OBJECT METHODS


OVERLOADING

The Exception::Class::Base object is overloaded so that stringification produces a normal error message. It just calls the as_string method described above. This means that you can just print $@ after an eval and not worry about whether or not its an actual object. It also means an application or module could do this:

 $SIG{__DIE__} = sub { Exception::Class::Base->throw( error => join '', @_ ); };

and this would probably not break anything (unless someone was expecting a different type of exception object from die).


OVERRIDING THE as_string METHOD

By default, the as_string method simply returns the value message or error param plus a stack trace, if the class's Trace method returns a true value or show_trace was set when creating the exception.

However, once you add new fields to a subclass, you may want to include those fields in the stringified error.

Inside the as_string method, the message (non-stack trace) portion of the error is generated by calling the full_message method. This can be easily overridden. For example:

  sub full_message
  {
      my $self = shift;
      my $msg = $self->message;
      $msg .= " and foo was " . $self->foo;
      return $msg;
  }


USAGE RECOMMENDATION

If you're creating a complex system that throws lots of different types of exceptions, consider putting all the exception declarations in one place. For an app called Foo you might make a Foo::Exceptions module and use that in all your code. This module could just contain the code to make Exception::Class do its automagic class creation. Doing this allows you to more easily see what exceptions you have, and makes it easier to keep track of them.

This might look something like this:

  package Foo::Bar::Exceptions;
  use Exception::Class ( Foo::Bar::Exception::Senses =>
                        { description => 'sense-related exception' },
                         Foo::Bar::Exception::Smell =>
                         { isa => 'Foo::Bar::Exception::Senses',
                           fields => 'odor',
                           description => 'stinky!' },
                         Foo::Bar::Exception::Taste =>
                         { isa => 'Foo::Bar::Exception::Senses',
                           fields => [ 'taste', 'bitterness' ],
                           description => 'like, gag me with a spoon!' },
                         ... );

You may want to create a real module to subclass Exception::Class::Base as well, particularly if you want your exceptions to have more methods.


OTHER EXCEPTION MODULES (try/catch syntax)

If you are interested in adding try/catch/finally syntactic sugar to your code then I recommend you check out U. Arun Kumar's Error.pm module, which implements this syntax. It also includes its own base exception class, Error::Simple.

If you would prefer to use the Exception::Class::Base class included with this module, you'll have to add this to your code somewhere:

  push @Exception::Class::Base::ISA, 'Error';

It's a hack but apparently it works.


AUTHOR

Dave Rolsky, <autarch@urth.org>


SEE ALSO

Devel::StackTrace - used by this module to create stack traces

Error.pm - implements try/catch in Perl. Also provides an exception base class.

Test::Exception - a module that helps you test exception based code.

Numerous other modules/frameworks seem to have their own exception classes (SPOPS and Template Toolkit, to name two) but none of these seem to be designed for use outside of these packages.

 Exception::Class - A module that allows you to declare real exception classes in Perl