黑马程序员技术交流社区
标题: try可以单独使用 [打印本页]
作者: iWilliam 时间: 2014-6-9 23:12
标题: try可以单独使用
关于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关键字不能单独使用了~
作者: xp8812 时间: 2014-6-9 23:22
感谢楼主让我明白了这个知识
作者: a6217815 时间: 2014-6-9 23:36
所以就是只拿到异常但是不处理吗?那这样拿到异常是为了什么?
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) |
黑马程序员IT技术论坛 X3.2 |