Re: Handling exceptions
<ahjiang@gmail.com> wrote :
Lets say i have this method
int foo() {
try {
do something;
return SUCCESS;
}catch(Exception e){
print e;
}finally{
return FAILURE;
}
}
I understand that failure will always be returned because of the
finally clause.
What is the best practice to return a value if success or failure.
Or should the exception be propagated to the calling method?
Generally speaking, my preference would be to propagate some sort of
exception rather than return a success code.
Your method would then look something like this:
void foo() throws FooException {
try {
do something;
} catch (SomethingException e) {
throw new FooException(e);
}
}
The caller of the method need not write code like this:
if(foo() != SUCCESS){
recover
}
more stuff
(This hides the fact that foo() is being called inside a conditional, and
places the recovery code -- which isn't necessarily the main flow of the
program -- right next to the callpoint.)
But instead the calling code looks more like:
try{
foo();
more stuff
} catch (FooException e) {
recover
}
(This makes the call to foo() about as explicit as can be, and the recovery
code is nicely isolated, away from the main flow of the program.)
OK, now for quibbling:
I generally like the exceptions approach for those situations that are truly
exceptional -- making it worth your while to abruptly terminate your caller
and force it to do something it wouldn't usually. If instead, there are a
variety of situations that can normally be expected to happen, and your
caller should be expected to know about and handle them all, then returning
some sort of status code is just fine in my book. What's more appropriate
depends on the situation and is something of a judgment call in any case.
What really gets my goat is "catch Throwable" or its only slightly less
pernicious twin, "catch Exception". These are too general and should almost
never be written.
-- Adam Maass