Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical

Re: Error Handling with Packages

by sasikumar (Monk)
on May 23, 2005 at 16:11 UTC ( #459610=note: print w/replies, xml ) Need Help??

in reply to Error Handling with Packages

Hi Dru,

I had such problems. I tried to avaoid it this way. All my custom packages functions will return me two variable instead of one. For eg:
#Function inside a package sub test() { ... ... open(FILE,"filename") || return (1,"Error while trying to open the fil +e filename"); .... return (0,UNDEF); } # Main Program my ($result,$err)=test(); Now based on the return value i decide to print the error or take corr +ective messures

There are lot of other ways to do it too. But i found this to be easier for me.


Replies are listed 'Best First'.
Re^2: Error Handling with Packages
by salva (Canon) on May 23, 2005 at 19:00 UTC
    Returning the error as a second value is usually not a good idea. It requires too much discipline to always check the error status, after every call, and it doesn't allow for idiomatic checks as
    foo() or die "foo failed";
    so lazy programmers will just don't do it resulting on the worst kind of errors: unnoticed errors!

    Usually it's much better to croak(): module users would still be able to handle errors via eval if they wish, and when not, the final user will notice that something went wrong because the croak will reach them.

      I have another custom approach:

      This way the module user can still use idioms like

      $O->foo() or die "could not blabla: ".$O->error();

      Users can still set the error handler to croak() if they wish. This could be extended ad nauseam: $debug switches, $exec_handler switch, method to get errMsg without resetting it -- you name it. I should probably put it in its own module, too, and inherit from that. I'm still not sure how to escalate errors when one method calls another. Maybe simply

      sub bar { my ($self) = @_; foo() or return raiseError("bar failed to rhubarb: ".$self->error( +)); return 1; } # ... $O->bar() or die "could not blabla: ".$O->error(); # "could not blabla: bar failed to rhubarb: foo: could not do thisandt +hat"

Log In?

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

How do I use this? | Other CB clients
Other Users?
Others perusing the Monastery: (3)
As of 2023-02-04 20:59 GMT
Find Nodes?
    Voting Booth?
    I prefer not to run the latest version of Perl because:

    Results (31 votes). Check out past polls.