Programming and Problem Solving with Java

(やまだぃちぅ) #1
5.2 Looping | 231

if (inLine == null) // If EOF
number = 0; // Set number to 0
else
number = Integer.parseInt(inFile.readLine()); // Convert number
}
}


We’ve usedparseIntpreviously but we haven’t includedNumberFormatException
in thethrowsclause ofmain. Why is it different from theIOExceptionthat we must
list in athrowsclause when we use file I/O? The reason is that Java defines two
kinds of exceptions, caught and uncaught.Caught exceptionsmust be caught or ex-
plicitly forwarded with athrowsclause.Uncaught exceptionsmay be optionally
caught, or they can be allowed to pass automatically to the JVM.
NumberFormatExceptionis an uncaught exception so it does not have to be listed in
athrowsclause, whileIOExceptionis an example of a caught exception that must
be explicitly thrown.
Caught exceptions usually indicate error conditions that are unlikely to oc-
cur, while uncaught exceptions are intended for errors that every good pro-
grammer is careful to avoid, such as division by zero. If we had to list every possible
uncaught exception in the heading of main, then it would be several lines long. Instead of mak-
ing us do so, the designers of the Java library simply assume that our code is carefully writ-
ten to avoid these common errors. If one of them does occur, the error is automatically
forwarded to the JVM, and our application crashes. In response, we identify the source of the
error, and then we correct the algorithm and the corresponding code to avoid further crashes.
To keep our examples short and understandable, we often omit tests for uncaught ex-
ceptions in this book. However, in writing code for actual applications, you should always try
to avoid such potential sources of crashes.


Summing Another common looping task is to sum a set of data values. Notice in the follow-


ing example that the summing operation is written the same way, regardless of how the
loop is controlled:


sum = 0; // Initialize sum
count = 1;
while(count <= 10)
{
number = Integer.parseInt(dataFile.readLine()); // Input a value
sum = sum + number; // Add value to sum
count++;
}


We initializesumto 0 before the loop starts so that the first time the loop body executes,
the statement


sum = sum + number;


Caught exception An excep-
tion in Java that must either be
caught with a catchstatement
or explicitly thrown to the next
level
Uncaught exception An ex-
ception in Java that can option-
ally be caught or allowed to
propagate automatically to the
next level
Free download pdf