Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

Re: How do I report an error back to the user of my object?

by kcott (Archbishop)
on Jun 04, 2012 at 22:32 UTC ( [id://974389]=note: print w/replies, xml ) Need Help??


in reply to How do I report an error back to the user of my object?

$! is a special global variable that you shouldn't be modifying yourself. Take a look at perlvar - Error Variables; in particular, the section describing when $! is meaningful and meaningless.

The first thing I'd do would be to move the error handling code into the module by changing the if statement to:

if (! $self->loaddata()) { die "Error loading data!"; } return $self;

Now users of your module don't need to type  or die "$!" after every call to the constructor.
( Side issue: your hard-coded undef will evaluate to false but so will 0 (zero) and '' (empty string) - using defined will provide a more robust solution. )

Your loaddata() routine may be performing operations which could also raise fatal exceptions, such as opening a file, connecting to a database, and so on. You can trap these errors with eval like this:

eval { $self->loaddata() }; if ($@) { die "Error loading data! Reason: $@"; } return $self;

You may want to use croak instead of die - see Carp. The first sentence of the description: "The Carp routines are useful in your own modules because they act like die() or warn(), but with a message which is more likely to be useful to a user of your module.".

One final point related to the use of bless in your code. You have the single-argument form (bless $self); the two-argument form (bless $self => $class) is preferred.

-- Ken

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others chanting in the Monastery: (7)
As of 2024-04-25 15:47 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found