A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© iWilliam 中级黑马   /  2014-6-9 23:12  /  1532 人查看  /  2 人回复  /   1 人收藏 转载请遵从CC协议 禁止商业使用本文

关于try关键字的问题,我以前也一直以为必须和catch或者finally配合使用,直到看到这个
The try-with-resources statement is a try statement that declares one or more resources. A resource is as an object that must be closed after the program is finished with it. The try-with-resources statement ensures that each resource is closed at the end of the statement. Any object that implements java.lang.AutoCloseable, which includes all objects which implement java.io.Closeable, can be used as a resource.
The following example reads the first line from a file. It uses an instance of BufferedReader to read data from the file. BufferedReader is a resource that must be closed after the program is finished with it:

static String readFirstLineFromFile(String path) throws IOException {  try (BufferedReader br = new BufferedReader(new FileReader(path))) {   
return br.readLine();
}
}
所以,大家以后不能再误导别人说try关键字不能单独使用了~


2 个回复

倒序浏览
感谢楼主让我明白了这个知识
回复 使用道具 举报
所以就是只拿到异常但是不处理吗?那这样拿到异常是为了什么?
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马