thinking in java 中的一個例子,這個慣用法保證了在構(gòu)造方法中拋出異常的代碼能夠正常處理:
1 package test ; 2 3 import java.io.BufferedInputStream; 4 import java.io.File; 5 import java.io.FileInputStream; 6 import java.io.IOException; 7 8 class InputFile { 9 PRivate BufferedInputStream in = null ;10 private File file = null ;11 public InputFile(String filepath ) throws IOException {12 file = new File(filepath) ;13 in = new BufferedInputStream(new FileInputStream(file));14 15 }16 public String getFileContent() throws IOException {17 byte[] content = new byte[(int)file.length()] ;18 in.read(content) ;19 return new String(content) ;20 }21 public void dispose() throws IOException{22 in.close(); 23 System.out.println("dispose successful ! ");24 }25 }26 public class Cleanup{27 public static void main(String[] args) {28 try{29 InputFile input = new InputFile("這里寫文件路徑") ;30 try{31 String content = input.getFileContent() ;32 }catch(Exception e ){33 e.printStackTrace();34 }35 finally{36 input.dispose(); 37 }38 }catch(Exception e){39 e.printStackTrace();40 }41 }42 }在main方法中可以確保文件正常打開才執(zhí)行dispose方法,也就是關(guān)閉文件的方法。
還有將InputFile類構(gòu)造方法中的異常拋出是有意義的,書上原話為:
“異常被重新拋出,對于構(gòu)造器而言這么做是很合適的,因為你總不希望去誤導(dǎo)調(diào)用方,讓他以為這個對象已經(jīng)創(chuàng)建完畢,可以使用了”
上面的編碼格式可以擴展廣泛一點,基本規(guī)則是:“在創(chuàng)建需要清理的對象之后,立即進(jìn)入一個try-fianlly語句塊”:
分為兩種情況,1 : 構(gòu)造方法可能會失敗也就是可能會拋出異常 2 : 構(gòu)造方法不會失敗
當(dāng)構(gòu)造方法不會拋出異常的情況:
1 class TestClean1 { 2 public TestClean1() { 3 // 比如打開了很多資源 4 } 5 /** 6 * 執(zhí)行該類的清理工作 7 */ 8 public void clean(){} 9 }10 class TestClean2 {11 public TestClean2() {12 }13 /**14 * 執(zhí)行該類的清理工作15 */16 public void clean(){}17 }18 public class TestCleanup {19 public static void main(String[] args) {20 21 TestClean1 clean1 = new TestClean1() ;22 TestClean2 clean2 = new TestClean2() ;23 try{24 // 在這里執(zhí)行clean1和2的代碼25 }finally{26 clean1.clean();27 clean2.clean();28 }29 }30 }當(dāng)構(gòu)造器會出現(xiàn)錯誤的時候:
1 class TestClean1 { 2 public TestClean1() throws Exception { 3 throw new Exception() ; 4 } 5 /** 6 * 執(zhí)行該類的清理工作 7 */ 8 public void clean(){} 9 }10 class TestClean2 {11 public TestClean2() throws Exception {12 throw new Exception() ;13 }14 /**15 * 執(zhí)行該類的清理工作16 */17 public void clean(){}18 }19 public class TestCleanup {20 public static void main(String[] args) {21 try{22 TestClean1 clean1 = new TestClean1() ;23 try{24 TestClean2 clean2 = new TestClean2() ;25 try{26 // 執(zhí)行clean1和clean2的代碼27 }finally{28 clean2.clean();29 }30 }catch(Exception e ){31 System.out.println("clean2構(gòu)造失敗");32 e.printStackTrace();33 }finally{34 clean1.clean();35 }36 }catch(Exception e ){37 System.out.println("clean1構(gòu)造失敗");38 e.printStackTrace();39 }40 }41 }當(dāng)構(gòu)造方法拋出異常表示沒有正常打開資源,也就不需要清理。上面代碼保證了兩個對象都能夠正確的清理。
新聞熱點
疑難解答