Dave Rolsky > Exception-Class-1.35 > Exception::Class

Download:
Exception-Class-1.35.tar.gz

Dependencies

Annotate this POD (7)

Related Modules

Object::InsideOut
Class::DBI
Log::Log4perl
CGI::Carp
Data::Dumper
Devel::StackTrace
Test::More
Image::Magick
HTML::Mason
Test::Exception
more...
By perlmonks.org

CPAN RT

New  2
Open  0
Stalled  1
View/Report Bugs
Module Version: 1.35   Source   Latest Release: Exception-Class-1.39

NAME ^

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

VERSION ^

version 1.35

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.' ) };

  my $e;

  # catch
  if ( $e = Exception::Class->caught('MyException') ) {
      warn $e->error, "\n", $e->trace->as_string, "\n";
      warn join ' ', $e->euid, $e->egid, $e->uid, $e->gid, $e->pid, $e->time;

      exit;
  }
  elsif ( $e = Exception::Class->caught('ExceptionWithFields') ) {
      $e->quixotic ? do_something_wacky() : do_something_sane();
  }
  else {
      $e = Exception::Class->caught();
      ref $e ? $e->rethrow : die $e;
  }

  # 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.

You will also want to look at the documentation for Exception::Class::Base, which is the default base class for all exception objects created by this module.

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.

Catching Exceptions ^

Exception::Class provides some syntactic sugar for catching exceptions in a safe manner:

  eval {...};

  if ( my $e = Exception::Class->caught('My::Error') ) {
      cleanup();
      do_something_with_exception($e);
  }

The caught() method takes a class name and returns an exception object if the last thrown exception is of the given class, or a subclass of that class. If it is not given any arguments, it simply returns $@.

You should always make a copy of the exception object, rather than using $@ directly. This is necessary because if your cleanup() function uses eval, or calls something which uses it, then $@ is overwritten. Copying the exception preserves it for the call to do_something_with_exception().

Exception objects also provide a caught method so you can write:

  if ( my $e = My::Error->caught() ) {
      cleanup();
      do_something_with_exception($e);
  }

Uncatchable Exceptions

Internally, the caught() method will call isa() on the exception object. You could make an exception "uncatchable" by overriding isa() in that class like this:

 package Exception::Uncatchable;

 sub isa { shift->rethrow }

Of course, this only works if you always call Exception::Class->caught() after an eval.

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.

Subclassing Exception::Class::Base

As part of your usage of Exception::Class, you may want to create your own base exception class which subclasses Exception::Class::Base. You should feel free to subclass any of the methods documented above. For example, you may want to subclass new() to add additional information to your exception objects.

Exception::Class FUNCTIONS ^

The Exception::Class method offers one function, Classes(), which is not exported. This method returns a list of the classes that have been created by calling the Exception::Class import() method. Note that this is all the subclasses that have been created, so it may include subclasses created by things like CPAN modules, etc. Also note that if you simply define a subclass via the normal Perl method of setting @ISA or use base, then your subclass will not be included.

Try::Tiny ^

If you are interested in adding try/catch/finally syntactic sugar to your code then I recommend you check out Try::Tiny. This is a great module that helps you ignore some of the weirdness with eval and $@.

SUPPORT ^

Please submit bugs to the CPAN RT system at http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Exception%3A%3AClass or via email at bug-exception-class@rt.cpan.org.

DONATIONS ^

If you'd like to thank me for the work I've done on this module, please consider making a "donation" to me via PayPal. I spend a lot of free time creating free software, and would appreciate any support you'd care to offer.

Please note that I am not suggesting that you must do this in order for me to continue working on this particular software. I will continue to do so, inasmuch as I have in the past, for as long as it interests me.

Similarly, a donation made in this way will probably not make me work on this software much more, unless I get so many donations that I can consider working on free software full time, which seems unlikely at best.

To donate, log into PayPal and send money to autarch@urth.org or use the button on this page: http://www.urth.org/~autarch/fs-donation.html

AUTHOR ^

Dave Rolsky <autarch@urth.org>

COPYRIGHT AND LICENSE ^

This software is Copyright (c) 2010 by Dave Rolsky.

This is free software, licensed under:

  The Artistic License 2.0 (GPL Compatible)
syntax highlighting: