1.6和以前是这样的,但这样的缺点是finally中也可能报错(如关闭流):
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(""));
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null)
br.close();
}
1.7新增try-with-resources 语句:
try (BufferedReader br = new BufferedReader(new FileReader(""))) {
br.readLine();
}
1.7中只要实现了AutoCloseable或Closeable接口的类或接口,都可以使用try-with-resource来实现异常处理和资源关闭。
public abstract class Reader implements Readable, Closeable
public interface Closeable extends AutoCloseable