Re: java exception handling
polaris wrote:
i was arguing with my manager about whether it's better to throw
exception from a service that im developing or to give the user
returned value. My supporting points are:
1-thowing exception is much mostly than returned value in term of
performance.
The impact of try-catch blocks when they are not used has become
negligible and the performance impact is not terrible when they are
used. But any performance gained is on the order of several machine
cycles, which is not enough to impact such a major architecture decision.
2-in returned value way the user can customize the behavior of the
system as he like and he would have clear view of the service result.
But values may be in imperfect states. A lazy user might not realize
that failures could happen and important code could blow up in his face.
3-with respect to the user requirement he doesn't really need a
returned value or exception from
the service.
If something is wrong, he needs to know. Period, full stop, end of story.
my manager supporting points:
1-the service should be general so in future if somebody want to be
informed by the result of
the service we don't have to modify it.
but infact if we consider all the assumption we will delf into hunders
of assumptions and if this is nessary the returned value is better way
than throwing exception.
How so? I sense some C or C++ assumptions coming into play here.
2. An exception can force the user to deal with the error. The user is
often in the best seat to decide whether or not he should repair the
situation or forcibly terminate.
3. Exceptions can provide finer granularity control over errors. Imagine
if Class.getMethod simply returned null instead of throwing an
exception. It would be difficult to tell if it was because the method
didn't exist or if it was merely insufficient access, the difference
between which may be important.
4. Hijacking the return values makes chaining operations difficult.
Class.forName(className).getMethod(name, args); is a somewhat common
idiom for code needing reflection. Should forName return null on error,
I would have to check for nullity first.
You also have not fully described what the circumstances are. In
general, the Java API often provides a good role model to follow. The
only times where it uses return values is where failure is not
exceptional, e.g., adding a method to a Set.
im very sorry for my long plah plah plah
The proper term I believe is "pontification."
any one have a comment.
One nit: try to use some more capitalization and spacing between
paragraphs. It's easier on eyes.
--
Beware of bugs in the above code; I have only proved it correct, not
tried it. -- Donald E. Knuth