Exception Catching
eric256
created: 2006-04-01 12:20:40

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 [cpan://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
Re: Exception Catching
created: 2006-04-01 13:08:30
[mod://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) };
}

perlmonks.org content © perlmonks.org and Arunbear, eric256

prlmnks.org © 2006 edmund von der burg (eccles & toad)

v 0.03