Java Reference
In-Depth Information
The Why
The reasoning behind the exception mechanism in Java is pretty simple. Bad things can hap-
pen, even to good programs. When such a bad thing happens, there is a need to react to it,
either by figuring out some other way to accomplish what was trying to be done when the bad
thing happened, by cleaning up and gracefully exiting, or by aborting the operation in which
the bad thing happened and trying something else. But the code that deals with the problem
shouldn't be mixed in with the code that is used when bad things don't happen, or the program
can rapidly become unreadable. In addition, programmers are probably better off if they have
to deal with problems as close as possible to the time and place that they occur.
The design also ties into the Java type system. Since an exception is an alternative return
value, it forms part of the signature of the method. Not declaring an exception would be like
not having to declare the type of the return value. It would be very difficult to write predictable
code in such a situation, and it would be difficult for the compiler to help you find mistakes.
Finally, the exception mechanism allows a program to separate the mainline code and the
error-handling code. Those of us who grew up in the C or C++ tradition of coding (especially
early C++, before exceptions were introduced there) are familiar with code that looked
something like:
returnValue = makeCall(somearg1, somearg2);
if (returnValue == someImpossibleValue) {
//take care of the error
returnValue1 = makeAnotherCall(somearg3);
if (returnValue1 == someOtherImpossibleValue){
//More error code
This leads to some interesting challenges when one wants to write clear code. The obvious one
is that the error-handling code interrupts the flow of the main code. After every call to some
function or method in which something bad can happen, the code first has to check whether
everything is OK and, if not, do something in response. The flow of the code is broken, and
when there is a common way to respond to some problem, a lot of code is duplicated (even if
the duplication is to call the same function that does the error handling).
Even worse, this approach requires that we mix in the return of standard values for a function
or method with the return values that mark an error. In C, the standard was to hand back a
Search WWH ::

Custom Search