Java教程是针对JDK 8编写的。本页面中描述的示例和实践不利用后续版本中引入的改进,并且可能使用不再可用的技术。
请参阅Java语言更改,了解Java SE 9及后续版本中更新的语言功能的摘要。
请参阅JDK发行说明,了解所有JDK版本的新功能、增强功能以及被删除或弃用的选项的信息。
try {
} finally {
}
try语句没有catch块,但有finally块,也是合法的。如果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标记后,程序尝试再次读取流。答案:
ListOfNumbers.java中添加一个readList方法。这个方法应该从一个文件中读取int值,打印每个值,并将它们追加到向量的末尾。你应该捕获所有适当的错误。你还需要一个包含要读取的数字的文本文件。
答案: 请参见 .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("文件: %s 未找到%n", file);
} catch(IOException e) {
System.err.println(e.toString());
} finally {
if (input != null) {
try {
input.close();
} catch(IOException io) {
}
}
}
}