So I've been experimenting with Exceptions, how to throw them, how to catch them, etc. While there is lots of info on this subject, there seems very little hard code you can use in actualy code. So I played some and here is what I came up with.

use strict; use warnings; use Data::Dumper; use Error; { package Error::MyError; @Error::MyError::ISA = qw(Error::Simple); sub catch { my $class = shift; return undef unless $@; return 1 if $@->isa($class); return 0; } } @Error::NextLevel::ISA = qw(Error::MyError); eval { throw Error::NextLevel("TEST"); 0; }; if (catch Error::NextLevel ) { print "Caught: " . $@->text; };

I use Error but only for its error object. On that error object i then overrode the catch method to be a little less magic which seems to result in it working better. Makeing use of inderict object notation we get a fairly nice syntax with little/no magic.

Please let me know what you think and what i screwed up ;)


___________
Eric Hodges

Replies are listed 'Best First'.
Re: Exception Catching
by Arunbear (Prior) on Apr 01, 2006 at 18:08 UTC
    Exception::Class::TryCatch also provides a catch routine, e.g. (straight from the POD)
    use Exception::Class::TryCatch; # simple usage of catch() eval { Exception::Class::Base->throw('error') }; catch my $err and warn $err->error; # catching only certain types or else rethrowing eval { Exception::Class::Base::SubClass->throw('error') }; catch( my $err, ['Exception::Class::Base', 'Other::Exception'] ) and warn $err->error; # catching and handling different types of errors eval { Exception::Class::Base->throw('error') }; if ( catch my $err ) { $err->isa('this') and do { handle_this($err) }; $err->isa('that') and do { handle_that($err) }; }