java finally close_java – 这个finally子句包含close()调用的原因是什么

我正在学习在线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&作家没有关闭,但是那个程序呢还没有关闭他们呢?

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值