阿里巴巴Java開發手冊 梳理筆記 - finally 塊必須對資源對象、流對象進行關閉
規約內容:
2.1 異常處理
6. 【強制】 finally 塊必須對資源對象、流對象進行關閉,有異常也要做 try - catch 。
說明:如果 JDK 7 及以上,可以使用 try - with - resources 方式。
jdk 7 之前:
@Test
public void test1() throws IOException {
String filepath = "D:\\gui-config.json";
BufferedReader br = null;
String curline;
try {
br = new BufferedReader(new FileReader(filepath));
while ((curline = br.readLine()) != null) {
System.out.println(curline);
}
} catch (FileNotFoundException e) {
throw new FileNotFoundException("文件xxx不存在,請檢查後重試。");
// trturn xxx;
} catch (IOException e) {
throw new IOException("文件xxx讀取異常。");
} finally {
try {
if (br != null) {
br.close();
}
} catch (IOException e) {
throw new IOException("關閉流異常。");
}
}
}
jdk 7 及以上
@Test
public void test2() throws IOException {
String filepath = "D:\\gui-config.json";
try (
FileReader fileReader = new FileReader(filepath);
BufferedReader br = new BufferedReader(fileReader)
) {
String curline = null;
while ((curline = br.readLine()) != null) {
System.out.println(curline);
}
}
}