我正在学习在线java课程,
Introduction to programming Using Java。
在I / O章节中,介绍了以下代码:
By the way, at the end of this program, you’ll find our first useful example of a finally clause in a try statement. When the computer executes a try statement, the commands in its finally clause are guaranteed to be executed, no matter what.
该程序在11.2.1节结束,是一个简单的程序,只需从文件中读取一些数字,并以相反的顺序写入它们。
主要方法中的相关代码是(数据是Reader,结果是Writer):
try {
// Read numbers from the input file, adding them to the ArrayList.
while ( data.eof() == false ) { // Read until end-of-file.
double inputNumber = data.getlnDouble();
numbers.add( inputNumber );
}
// Output the numbers in reverse order.
for (int i = numbers.size()-1; i >= 0; i--)
result.println(numbers.get(i));
System.out.println("Done!");
} catch (IOException e) {
// Some problem reading the data from the input file.
System.out.println("Input Error: " + e.getMessage());
} finally {
// Finish by closing the files, whatever else may have happened.
data.close();
result.close();
}
所以我想知道为什么finally子句在这种情况下是有用的,当没有其他退出点从try或catch子句。不是密切的方法只是在主体的身体吗?
我以为也许是因为理论上可能会有一些其他的RuntimeException可能导致程序崩溃,然后离开Reader&作家没有关闭,但是那个程序呢还没有关闭他们呢?