2012-05-21 11 views
0

我想拋出一個異常,該方法期望只有一個元素的列表,並且我想拋出一個異常如果列表中有多個。我試圖確定是否存在適合現有的Java異常來處理這種情況。我試着目睹了名單here,但沒有看到任何跳出正確的東西。當期望只有一個值但存在很多值時拋出什麼內置異常

在這種情況下,我調用一個對象的方法,期望該方法將所述列表引用爲對象的屬性。所以我實際上沒有傳遞數組,也沒有索引作爲參數。

(編輯澄清)

回答

4

既然你想暗示給定的輸入是不是有效的,你應該有一個消息,說明了同樣的理由使用IllegalArgumentException

throw new IllegalArgumentException("Input specified has more elements then expected"); 

否則,你可以有自己的Exception中唯一定義的條件。

儘管我以某種方式感受到因爲它的異常原因的元素數量,您甚至可以使用IndexOutOfBoundsException,這在給定的場景中是有意義的。

throw new IndexOutOfBoundsException("Expected size is 1, submitted input has size " + list.size()); 

編輯:按照鑑於名單評論

不是方法調用的一部分,但屬於它的方法被調用的對象,在這種情況下list.size() > 1意味着對象未處於正確的狀態,並與定製版本IllegalStateExceptionIllegalStateException本身具有適當的錯誤消息會更合適。

+0

嗯期間nperformed,我曾想過,但該方法是參照所述列表作爲的屬性在這種情況下,我呼籲的對象上的方法,期望目的。所以我實際上沒有傳遞數組,也沒有索引作爲參數,所以我認爲IllegalArgumentException可能不適合這個法案。也許按照我所定義的方法調用該方法是符合條件的(或者我需要重新考慮我的方法簽名)。 –

+0

@JoshDiehl:所以,你的問題其實並沒有描述你想要做什麼?請更正您的問題 - 包括少量代碼,證明情況會有用。 –

+0

@JoshDiehl我編輯了我的答案 – mprabhat

3

你可以讓自己的異常,並把它。

public MyException extends Exception { 
} 

if(list.size() > 1) { 
    throw new MyException("Expected only 1 element, found: " + list.size()); 
} 
0

你可以扔誤差修改的方法是這樣

public void someMethod(List<MyClass> myList) throws NullPointerException, IllegalArgumentException { 
    if (myList == null) 
     throw new NullPointerException("myList parameter can't be null"); 
    if (myList.size() > 1) { 
     throw new IllegalArgumentException("myList parameter must contain only 1 parameter"); 
    } 
    //your code here... 
} 

這將是更好的設置錯誤消息的屬性文件,這樣就只需要改變配置,以顯示新的消息,沒有需要通過修改代碼來重寫錯誤消息。

1

如果列表是您調用方法的對象的字段,那麼您可以說具有錯誤大小列表的對象處於錯誤狀態,因此IllegalStateException將是適當的。

但實際上,您應該用標量字段替換列表(List<Foo>變爲Foo),這樣甚至不會出現這種情況。

0

我不知道我理解的使用情況,所以這個答案可能是關閉基地,但我會建議一個AssertionError這種方法的

List <T> answers ; // expection a list of size one 
assert 1 == list . size () : "The programmer expects that there will be one and only one answer" 
/* 
In development: assertions enabled, 
If there are zero answers, the program will crash on the assertion. 
If there are multiple answers, the program will crash on the assertion. 
Only if there is exactly one answer will it proceed to the below line (and work correctly). 
In production: assertions disbled, 
If there are zero answers, the program will throw a RuntimeException on the below line. 
If there are multiple answers, the program will proceed to the below line (and appear to work). 
If there is only one answer, the program will proceed to the below line and wok correctly. 
*/ 
T answer = answers . get (0) ; 

優勢在使用ifswitch

  1. 一些代碼覆蓋工具會希望你爲分支編寫單元測試。
  2. 分支增加了圈複雜度。
  3. 評估是唯一的發展
相關問題