2012-07-10 44 views
1

我在mClass構造如下代碼:處理空值,其中不允許

public mClass(Context ctx) { 
    super(); 
    this.ctx = ctx; 
} 

上下文不能爲空,因爲它necesary爲對象的操作。所以如果我允許創建一個新的mClass(null),它將在稍後中斷。

當創建對象時,我想崩潰,因爲發生錯誤情況時。這是什麼標準的做法?

例如使

public mClass(Context ctx) { 
    super(); 
    if(ctx==null) throw new Exception ("...."); 
    this.ctx = ctx; 
} 

軍隊申報方法例外運動員,我不wan't這樣做,因爲傳遞一個空值是不常見

回答

7

java.lang.IllegalArgumentException

這是一個運行時異常,所以你不需要強行處理這個,如果它被拋出,應用程序將會崩潰(如果它沒有處理)

1

通過將類的構造函數設爲私有,從而確保客戶端只能通過構建器創建類的實例,從而可以避免throwing an exception from the constructor。建造者可以構造一個對象之前檢查所提供的構造函數依賴關係的有效性,如下圖所示:

public class MyClass { 

    public static class MyClassBuilder { 
     private Context ctx; 

     public MyClassBuilder setContext(Context ctx) { 
      this.ctx = ctx; 

      return this; 
     } 

     public MyClass build() { 
      if(ctx==null) { 
       throw new IllegalArgumentException (""); 
      } else { 
       return new MyClass(this.ctx); 
      } 
     } 
    } 

    private final Context ctx; 

    private MyClass(Context ctx) { 
     super(); 
     this.ctx = ctx; 
    } 
} 
1

如果MyClass不能負責構建自己的Context像你這樣,你應該把它注射。拋出RuntimeException或任何子類都會執行空檢查,但IllegalArgumentException在這裏最合適。

不要忘了讓ctx字段final,它會讓你的代碼更健壯。