Java 教程是为 JDK 8 编写的。本页中描述的示例和实践未利用在后续版本中引入的改进。
try {
} finally {
}
try 语句如果有 finally 块,则不必有 catch 块。如果 try 语句中的代码具有多个退出点且没有关联的 catch 子句,则无论 try 块如何退出都会执行 finally 块中的代码。因此,如果存在 必须始终 执行的代码,则提供 finally 块是有意义的。这包括资源恢复代码,例如关闭 I/O 流的代码。
catch (Exception e) {
}
答案:此处理程序捕获 Exception 类型的异常;因此,它捕获任何异常。这可能是一个糟糕的实现,因为你丢失了有关抛出的异常类型的有价值信息,并使你的代码效率降低。因此,你的程序可能会被迫确定异常类型,然后才能决定最佳恢复策略。
try {
} catch (Exception e) {
} catch (ArithmeticException a) {
}
Exception 类型的异常;因此,它捕获任何异常,包括 ArithmeticException。第二个处理程序永远无法到达。此代码将无法编译。int[] A;
A[0] = 0;classes.zip 或 rt.jar。)end of stream 标记的末尾。end of stream 标记之后,程序尝试再次读取流。答案:
readList 方法添加到 ListOfNumbers.java。此方法应从文件中读取 int 值,打印每个值,并将它们附加到 vector 的末尾。你应该捕获所有适当的错误。你还需要一个包含要读入的数字的文本文件。
答案:参见 .ListOfNumbers2.java
cat 方法,以便进行编译:
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();
}
}
}
答案:捕获异常的代码以粗体显示:
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) {
}
}
}
}