I didn't program Java for very long, so I really never quite understood the best way to handle exceptions. (The one thing that I miss in Perl is compile-time checking of whether or not the exceptions are caught, but that's a side issue). Recently, I was struggling to get an API just write (sic) and the simplest way to do it seemed to be the following:
my $data = $self->__validate_added_data;
if ( UNIVERSAL::isa( $data, 'Foo::Form' ) ) {
# add the data
}
else {
# process the error
}
In other words, if I get back a valid Form object, I can add the data to the database. Otherwise, I have a hashref that contains the form error information. This error information is user error -- not program error. As a result, I don't want to die or warn, yet variants of those are typical Perl error handling mechanisms. Further, I have a method that returns two fundamentally different types of data: and object or a hashref. I finally started using the Error.pm module and now use try/catch blocks to handle the types of errors that I need.
try {
my $data = $self->__validate_added_data;
# add the data
}
catch FormValidationError with {
# process the error
};
Combining this with Test::Exception has made my tests simpler and my code more self-documenting. I'm going to have to dig up some resources on "Best Practices" with exception handling. I like this.
Hmm ... I think I'll post this on Perlmonks and see what they have to say.
Re:Exception debate
Ovid on 2003-01-29T03:51:50
Absolutely wonderful writeup! That definitely makes the think that checked exceptions might not be the WunderTool that I thought. The problem appears to lie in programmers being pressed for time and thus "swallowing" exceptions with the intent to come back to them later. We all know what a lie "I'll do it tomorrow" is
try {:)
doSomethingWith(foo);
} catch (SomeException e) {}/* exception swallowed */ Knowing full well that I'm often under the gun at work, I could easily see myself doing that with every intent of coming back to it. Three thousand lines of code later
... There is one benefit to checked exceptions that I see. If I am using third-party software, I might not be aware of all of the exceptions that it throws. It would be nice to see the uncaught exceptions at compile time. Shipping a product after having failed to trap the YourCPUIsOverheating exception would definitely be a damper on my day (and perhaps my paycheck). Why would I fail to trap it? It's in the docs, right? And I'm going to read the docs tomorrow. Really.
Re:Closures
vbeilin on 2003-01-29T11:48:38
perhaps here?Re:Closures
Matts on 2003-01-29T13:40:13
Ooops, I meant 2002 not 2003.Re:Closures
Ovid on 2003-01-29T18:29:04
That's a great article. Thank you very much. That was certainly a pitfall that I was not anticipating