man 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 CWException::Class allows you to automagically create CWException::Class::Base subclasses. You can also create subclasses via the traditional means of defining your own subclass with CW@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:
- * isa
- This is the class's parent class. If this isn't provided then the class name in CW$Exception::Class::BASE_EXC_CLASS is assumed to be the parent (see below). This parameter lets you create arbitrarily deep class hierarchies. This can be any other CWException::Class::Base subclass in your declaration or a subclass loaded from a module. To change the default exception class you will need to change the value of CW$Exception::Class::BASE_EXC_CLASS before calling CWimport(). To do this simply do something like this: BEGIN { CW$Exception::Class::BASE_EXC_CLASS = 'SomeExceptionClass'; } If anyone can come up with a more elegant way to do this please let me know. CAVEAT: If you want to automagically subclass an CWException::Class::Base subclass loaded from a file, then you must compile the class (via use or require or some other magic) before you import CWException::Class or you'll get a compile time error.
- * fields
- This allows you to define additional attributes for your exception class. Any field you define can be passed to the CWthrow() or CWnew() methods as additional parameters for the constructor. In addition, your exception object will have an accessor method for the fields you define. This parameter can be either a scalar (for a single field) or an array reference if you need to define multiple fields. Fields will be inherited by subclasses.
- * alias
- Specifying an alias causes this class to create a subroutine of the specified name in the caller's namespace. Calling this subroutine is equivalent to calling CW<class>->throw(@_) for the given exception class. Besides convenience, using aliases also allows for additional compile time checking. If the alias is called without parentheses, as in CWthrow_fields "an error occurred", then Perl checks for the existence of the CWthrow_fields() subroutine at compile time. If instead you do CWExceptionWithFields->throw(...), then Perl checks the class name at runtime, meaning that typos may sneak through.
- * description
- Each exception class has a description method that returns a fixed string. This should describe the exception class (as opposed to any particular exception object). This may be useful for debugging if you start catching exceptions you weren't expecting (particularly if someone forgot to document them) and you don't understand the error messages.
The CWException::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
CWException::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 CWcaught() method returns an exception object if the last thrown exception is of the given class, or a subclass of that class. Otherwise it returns false.
You should always make a copy of the exception object, rather than using CW$@ directly. This is necessary because if your CWcleanup() function uses CWeval, or calls something which uses it, then CW$@ is overwritten. Copying the exception preserves it for the call to CWdo_something_with_exception().
Uncatchable Exceptions
Internally, the CWcaught() method will call CWisa() on the exception object. You could make an exception uncatchable by overriding CWisa() in that class like this:
package Exception::Uncatchable;
sub isa { shift->rethrow }
Of course, this only works if you always call CWException::Class->caught() after an CWeval.
Exception::Class::Base CLASS METHODS
- * Trace($boolean)
- Each CWException::Class::Base subclass can be set individually to include a a stracktrace when the CWas_string method is called. The default is to not include a stacktrace. Calling this method with a value changes this behavior. It always returns the current value (after any change is applied). This value is inherited by any subclasses. However, if this value is set for a subclass, it will thereafter be independent of the value in CWException::Class::Base. This is a class method, not an object method.
- * NoRefs($boolean)
- When a CWDevel::StackTrace object is created, it walks through the stack and stores the arguments which were passed to each subroutine on the stack. If any of these arguments are references, then that means that the CWDevel::StackTrace ends up increasing the refcount of these references, delaying their destruction. Since CWException::Class::Base uses CWDevel::StackTrace internally, this method provides a way to tell CWDevel::StackTrace not to store these references. Instead, CWDevel::StackTrace replaces references with their stringified representation. This method defaults to true. As with CWTrace(), it is inherited by subclasses but setting it in a subclass makes it independent thereafter.
- * RespectOverload($boolean)
- When a CWDevel::StackTrace object stringifies, by default it ignores stringification overloading on any objects being dealt with. Since CWException::Class::Base uses CWDevel::StackTrace internally, this method provides a way to tell CWDevel::StackTrace to respect overloading. This method defaults to false. As with CWTrace(), it is inherited by subclasses but setting it in a subclass makes it independent thereafter.
- * Fields
- This method returns the extra fields defined for the given class, as an array. This method creates a new object with the given error message. If no error message is given, CW$! is used. It then die's with this object as its argument. This method also takes a CWshow_trace parameter which indicates whether or not the particular exception object being created should show a stacktrace when its CWas_string() method is called. This overrides the value of CWTrace() for this class if it is given. The frames included in the trace can be controlled by the CWignore_class and CWignore_package parameters. These are passed directly to Devel::Stacktrace's constructor. See CWDevel::Stacktrace for more details. If only a single value is given to the constructor it is assumed to be the message parameter. Additional keys corresponding to the fields defined for the particular exception subclass will also be accepted.
- * new
- This method takes the same parameters as CWthrow(), but instead of dying simply returns a new exception object. This method is always called when constructing a new exception object via the CWthrow() method.
- * description
- Returns the description for the given CWException::Class::Base subclass. The CWException::Class::Base class's description is Generic exception (this may change in the future). This is also an object method.
Exception::Class::Base OBJECT METHODS
- * rethrow
- Simply dies with the object as its sole argument. It's just syntactic sugar. This does not change any of the object's attribute values. However, it will cause CWcaller() to report the die as coming from within the CWException::Class::Base class rather than where rethrow was called. Of course, you always have access to the original stacktrace for the exception object.
- * message
- * error
- Returns the error/message associated with the exception.
- * pid
- Returns the pid at the time the exception was thrown.
- * uid
- Returns the real user id at the time the exception was thrown.
- * gid
- Returns the real group id at the time the exception was thrown.
- * euid
- Returns the effective user id at the time the exception was thrown.
- * egid
- Returns the effective group id at the time the exception was thrown.
- * time
- Returns the time in seconds since the epoch at the time the exception was thrown.
- * package
- Returns the package from which the exception was thrown.
- * file
- Returns the file within which the exception was thrown.
- * line
- Returns the line where the exception was thrown.
- * trace
- Returns the trace object associated with the object.
- * show_trace($boolean)
- This method can be used to set whether or not a strack trace is included when the as_string method is called or the object is stringified.
- * as_string
- Returns a string form of the error message (something like what you'd expect from die). If the class or object is set to show traces then then the full trace is also included. The result looks like CWCarp::confess().
- * full_message
- Called by the CWas_string() method to get the message. By default, this is the same as calling the CWmessage() method, but may be overridden by a subclass. See below for details.
OVERLOADING
The CWException::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 CWprint $@ after an CWeval 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 CWdie()).
OVERRIDING THE as_string METHOD
By default, the CWas_string() method simply returns the value CWmessage or CWerror param plus a stack trace, if the class's CWTrace() method returns a true value or CWshow_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 CWas_string() method, the message (non-stack trace) portion of the error is generated by calling the CWfull_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 CWFoo::Exceptions module and use that in all your code. This module could just contain the code to make CWException::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 CWException::Class::Base as well, particularly if you want your exceptions to have more methods.
Subclassing Exception::Class::Base
As part of your usage of CWException::Class, you may want to create your own base exception class which subclasses CWException::Class::Base. You should feel free to subclass any of the methods documented above. For example, you may want to subclass CWnew() to add additional information to your exception objects.
Exception::Class FUNCTIONS
The CWException::Class method offers one function, CWClasses(), which is not exported. This method returns a list of the classes that have been created by calling the CWException::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 CW@ISA or CWuse base, then your subclass will not be included.
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 CWError.pm module, which implements this syntax. It also includes its own base exception class, CWError::Simple.
If you would prefer to use the CWException::Class::Base class included with this module, you'll have to add this to your code somewhere:
push @Exception::Class::Base::ISA, 'Error' unless 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.