try {
} finally {
}
try statement does not have to have a catch block if it has a finally block. If the code in the try statement has multiple exit points and no associated catch clauses, the code in the finally block is executed no matter how the try block is exited. Thus it makes sense to provide a finally block whenever there is code that must always be executed. This include resource recovery code, such as the code to close I/O streams.
catch (Exception e) {
}
Answer: This handler catches exceptions of type Exception; therefore, it catches any exception. This can be a poor implementation because you are losing valuable information about the type of exception being thrown and making your code less efficient. As a result, your program may be forced to determine the type of exception before it can decide on the best recovery strategy.
try {
} catch (Exception e) {
} catch (ArithmeticException a) {
}
Exception; therefore, it catches any exception, including ArithmeticException. The second handler could never be reached. This code will not compile.int[] A;
A[0] = 0;classes.zip or rt.jar.)end of stream marker.end of stream marker, a program tries to read the stream again.Answer:
readList method to
ListOfNumbers.java. This method should read in int values from a file, print each value, and append them to the end of the vector. You should catch all appropriate errors. You will also need a text file containing numbers to read in.
Answer: See
.ListOfNumbers2.java
cat method so that it will compile:
public static void cat(File file) {
RandomAccessFile input = null;
String line = null;
try {
input = new RandomAccessFile(file, "r");
while ((line = input.readLine()) != null) {
System.out.println(line);
}
return;
} finally {
if (input != null) {
input.close();
}
}
}
Answer: The code to catch exceptions is shown in bold:
public static void cat(File file) {
RandomAccessFile input = null;
String line = null;
try {
input = new RandomAccessFile(file, "r");
while ((line = input.readLine()) != null) {
System.out.println(line);
}
return;
} catch(FileNotFoundException fnf) {
System.err.format("File: %s not found%n", file);
} catch(IOException e) {
System.err.println(e.toString());
} finally {
if (input != null) {
try {
input.close();
} catch(IOException io) {
}
}
}
}