java 构造器(constructor)
生活随笔
收集整理的這篇文章主要介紹了
java 构造器(constructor)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
? 有一點很重要,即你要時刻詢問子句"如果異常發生了,所有東西能被正確清理碼?",盡管大多數情況下時非常安全的,但涉及到構造器時,問題出現了,構造器會把對象設置成安全的初始狀態,但還會又別的動作,比如打開一個文件,這樣的動作只有在對象使用完畢并且用戶調用了特殊的清理方法之后才能得以清理,如果在構造器內拋出了異常,這些行為也許就不能正常工作了,這意味著在編寫構造器時要格外細心.
? 用finally也許可以解決問起,但問題并非如此簡單,因為finally會每次都執行清理操作,如果構造器在執行過程中半途而廢,也許該對象的某部分還沒有創建成功就要被清理,這又會拋出新的異常(.close()也會拋出異常)
?1.構造器拋出異常要格外注意清理方法是否有必要調用,如果方法恰當,直接向上層拋出的確能簡化編程
package exceptions; //: exceptions/InputFile.java // Paying attention to exceptions in constructors. import java.io.*;public class InputFile {private BufferedReader in;public InputFile(String fname) throws Exception {try {in = new BufferedReader(new FileReader(fname));// Other code that might throw exceptions} catch(FileNotFoundException e) {System.out.println("Could not open " + fname);// Wasn't open, so don't close it //如果沒有打開文件就不需要關閉throw e;} catch(Exception e) {// All other exceptions must close it 如果時其它異常則必須關閉文件try { //in.close()也可能拋出異常,所有要放到try塊里面in.close();} catch(IOException e2) {System.out.println("in.close() unsuccessful");}throw e; // Rethrow} finally { //由于finally總會被執行,如果在這里關閉文件則文件剛打開還沒開始使用就關閉了// Don't close it here!!! }}public String getLine() {String s;try {s = in.readLine();} catch(IOException e) { //這這異常已被捕獲,因此getLine不會拋出任何異常throw new RuntimeException("readLine() failed");//重新拋出新的異常到上層環境,有時會簡化編程}return s;}public void dispose() {try {in.close();System.out.println("dispose() successful");} catch(IOException e2) {throw new RuntimeException("in.close() failed");}} } ///:~2.對于在構造器階段可能拋出的異常,并且要求清理的,最安全的使用方法時使用嵌套的try子句,
package exceptions; //: exceptions/Cleanup.java // Guaranteeing proper cleanup of a resource.public class Cleanup {public static void main(String[] args) {try {InputFile in = new InputFile("Cleanup.java");try {String s;int i = 1;while((s = in.getLine()) != null); // Perform line-by-line processing here...} catch(Exception e) {//這里捕捉的時getLine()方法重新拋出的異常System.out.println("Caught Exception in main");e.printStackTrace(System.out);} finally { //如果構造成功,則一定會執行in.dispose()清理 in.dispose();}} catch(Exception e) { //InputFile對象在自己的try語句塊優先,因此構造失敗會進入這里,而不會執行內部的try塊的in.colse()System.out.println("InputFile construction failed");}} } /* Output: dispose() successful *///:~?
3. 這種通用的清理慣用法在構造器不跑出任何異常時也應該應用,其基本規則時:在需要清理的對象之后,立即進入一個try-finally語句塊.
//基本上,你應該仔細考慮所有的可能細節,例如本例的dispose()如果可以拋出異常,那么就需要額外的try語句塊package exceptions; //: exceptions/CleanupIdiom.java // Each disposable object must be followed by a try-finallyclass NeedsCleanup { // Construction can't failprivate static long counter = 1;private final long id = counter++;public void dispose() {System.out.println("NeedsCleanup " + id + " disposed");} }class ConstructionException extends Exception {}class NeedsCleanup2 extends NeedsCleanup {// Construction can fail:public NeedsCleanup2() throws ConstructionException {} }public class CleanupIdiom {public static void main(String[] args) {// Section 1:NeedsCleanup nc1 = new NeedsCleanup();try {// ...} finally {nc1.dispose();}// Section 2:// If construction cannot fail you can group objects:// nc5 constructor 如果對象構造不能失敗就不需要任何catch//不能失敗的對象構造器對象可以群眾在一起NeedsCleanup nc2 = new NeedsCleanup();NeedsCleanup nc3 = new NeedsCleanup();try {// ...} finally {nc3.dispose(); // Reverse order of construction nc2.dispose();}// Section 3:// If construction can fail you must guard each one:try {NeedsCleanup2 nc4 = new NeedsCleanup2();try {NeedsCleanup2 nc5 = new NeedsCleanup2();try { //如果nc5對象構造失敗則會調用try塊清理,否則永不調用// ...} finally {nc5.dispose();}} catch(ConstructionException e) { System.out.println(e);} finally {nc4.dispose();}} catch(ConstructionException e) { // nc4 constructor System.out.println(e);}} } /* Output: NeedsCleanup 1 disposed NeedsCleanup 3 disposed NeedsCleanup 2 disposed NeedsCleanup 5 disposed NeedsCleanup 4 disposed *///:~
?
轉載于:https://www.cnblogs.com/jiangfeilong/p/10303179.html
總結
以上是生活随笔為你收集整理的java 构造器(constructor)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 项目管理中风险评价的必要性
- 下一篇: 【python数字信号处理】——scip