http://qs321.pair.com?node_id=230826


in reply to Re: Best Practices for Exception Handling
in thread Best Practices for Exception Handling

my method is similar, but different...

## let's say bar is a method in foo sub bar { my( $self, @args )= @_; eval { $self->method( @args ) }; $@ and $self->raise_error( @_ ) and return undef; } ## called like: my $foo= foo->new(); my $result= $foo->bar( @args ) or warn $foo->Error();

the method sets an error and returns undef, allowing the caller to deal with the error as it sees fit. of course, you might want to handle a method that can return 0 by using defined

~Particle *accelerates*

Replies are listed 'Best First'.
Re*Re^2: Best Practices for Exception Handling
by bart (Canon) on Jan 29, 2003 at 09:40 UTC
    of course, you might want to handle a method that can return 0 by using defined
    Or use the trick that some other modules use: return "0E0" or "0 but true" for zero, as a string. These are both true and 0, and do not produce warnings when converted into a number, the former because it's a normal floating point format, the latter because it's a hardcoded exception in perl.

    Now I come to think of it: you can use any normal format for zero, as long as it's not "0", for example "0.0".

Re^3: Best Practices for Exception Handling
by theguvnor (Chaplain) on Jan 29, 2003 at 02:06 UTC

    Cool.. that's the way I like to handle errors too; but I always wonder if it's the *best* way. This is an interesting thread - Ovid++

    Jon

Re: Re^2: Best Practices for Exception Handling
by demerphq (Chancellor) on Jan 29, 2003 at 17:06 UTC
    Personally I think the following little trick/modification makes for cleaner code... (and I think that raise_error makes more sense if it contains the error message returned...)
    sub bar { my( $self, @args )= @_; eval { $self->method( @args ); 1} or $self->raise_error( $@, @_ ) and return undef; }
    If you can contrive to make raise_error() return undef you can make it even cleaner
    sub bar { my( $self, @args )= @_; eval { $self->method( @args ); 1} or return $self->raise_error( $@, @_ ); }

    --- demerphq
    my friends call me, usually because I'm late....