Java Reference
In-Depth Information
It is important to have a well thought-out and consistent exception-
handling strategy for the sake of efficiency and good programming practice.
Exception handling should not be considered an afterthought, but an integral
part of the development process. Having a consistent exception-handling strat-
egy helps develop applications that are robust and dependable by design rather
than by accident. The Java Language Specification states that “an exception will
be thrown when semantic constraints are violated,” which implies that an excep-
tion throws in situations that ordinarily are not possible or in the event of a
violation of normal program behavior. Therefore, sometimes it is easier to
address data entry errors with simple if statements that display error messages,
rather than by throwing exceptions. On the other hand, if the error is related to
a type of exception that Java already is handling in the program, it makes sense
to reuse that catch code to validate the data entry.
Repetition Structure
Thus far in this program code, if the user enters an invalid or unreasonable
number, the program terminates. A message displays notifying the user of the
error, but it does not allow the user to reenter the data and try again without
rerunning the entire program. As previously noted, Java uses a repetition struc-
ture to repeat a certain section of code. This repetitive, or iterative, process is
referred to as looping . The Commission program will use a repetition structure
so that if the user enters an invalid or unreasonable number, it again displays
the Input dialog box so that the user can try again to enter valid and reasonable
data.
The while Statement
Java uses a special repetition structure, called a while loop , for looping
when the exact number of repetitions is unknown. To code a while loop, you
code a while statement , starting with the keyword, while, followed by a condi-
tion in parentheses. All of the code that should be repeated, or looped, while the
condition evaluates to true is enclosed in braces. Table 4-8 on the next page
shows the general form of the while statement. The repetition structure and the
while statement also are described in detail in Appendix A on page APP 8.
Search WWH ::




Custom Search