Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
PerlMonks  

Re^2: Best Practices for Exception Handling

by particle (Vicar)
on Jan 29, 2003 at 01:13 UTC ( #230826=note: print w/ replies, xml ) Need Help??


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*


Comment on Re^2: Best Practices for Exception Handling
Select or Download Code
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 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: 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....

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://230826]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others meditating upon the Monastery: (7)
As of 2014-07-11 03:13 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    When choosing user names for websites, I prefer to use:








    Results (217 votes), past polls