Java Reference
In-Depth Information
12.7. When to Use Exceptions
We used the phrase "unexpected error condition" at the beginning of this
chapter when describing when to throw exceptions. Exceptions are not
meant for simple, expected situations. For example, reaching the end of
a stream of input is expected, so the method that returns the next input
from the stream has "hitting the end" as part of its expected behavior. A
return flag that signals the end of input is reasonable because it is easy
for callers to check the return value, and such a convention is also easier
to understand. Consider the following typical loop that uses a return flag:
while ((token = stream.next()) != Stream.END)
process(token);
stream.close();
Compare that to this loop, which relies on an exception to signal the end
of input:
try {
for (;;) {
process(stream.next());
}
} catch (StreamEndException e) {
stream.close();
}
In the first case, the flow of control is direct and clear. The code loops
until it reaches the end of the stream, and then it closes the stream. In
the second case, the code seems to loop forever. Unless you know that
end of input is signaled with a StreamEndException , you don't know the
loop's natural range. Even when you know about StreamEndException , this
construction can be confusing since it moves the loop termination from
inside the for loop into the surrounding try block.
 
Search WWH ::




Custom Search