Steven Shaw wrote:

> Hi, I'm looking for tutorials/sample-code/book-recommendations for
> learning about exceptions, exception objects and their effective use.
> 
> Cheers,
> Steve.

you can do simply error handling with evel,$@ and the sort. if you build 
your error classes carefully, you can mimi (somewhat) Java's approach to 
exception handling as well:

!/usr/bin/perl -w
use strict;

#--
#-- here is my top error class which all sub error inherite from
#--
package Error;

use Exporter;

our @ISA = qw(Exporter);

use overload '""' => sub { return "Error: $_[0]->{errst}" };

sub new{
        my $class = shift;
        my $errst = shift;

        return bless {errst => $errst} => $class;
}

1;

__END__

!/usr/bin/perl -w
use strict;

#--
#-- this is to simulate i/o error which is a child class of error
#--
package IOError;

use Exporter;
use Error;

#--
#-- i/o error is a type of error
#--
our @ISA = qw(Exporter Error);

use overload '""' => sub { return "IOError: $_[0]->{errst}" };

sub new{
        my $class = shift;
        my $errst = shift;

        return bless {errst => $errst} => $class;
}

1;

__END__

the following shows how each of those works:

!/usr/bin/perl -w

use Error;
use IOError;

#--
#-- mimi Java's try
#--
eval{
        function(1);
};

#--
#-- mimi Java's catch with most specific error first
#-- and then all other error. catch the i/o error first
#-- and then just error of any kind. if no error, no error
#-- is printed
#--
if(UNIVERSAL::isa($@,"IOError")){
        print "$@\n";
}elsif(UNIVERSAL::isa($@,"Error")){
        print "$@\n";
}else{
        print "no error\n";
}

sub function{
        my $number = shift;
        if($number == 1){
                die new Error("Just an error");
        }elsif($number == 2){
                die new IOError("Just an IOError");
        }
}

__END__

prints:

Error: Just an error

you can build the class tree as deep as you want and with as many
different types of error as you want.

david

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]

Reply via email to