我有一個檢查二維數組中點的方法,它也檢查它們是否爲空。我想拋出ArrayIndexOutOfBoundsException
,因爲我已經檢查了null。如何拋出ArrayIndexOutOfBoundsException?
我嘗試在聲明方法後添加throws ArrayIndexOutOfBoundsException
,但它不起作用。我該怎麼做呢?
我有一個檢查二維數組中點的方法,它也檢查它們是否爲空。我想拋出ArrayIndexOutOfBoundsException
,因爲我已經檢查了null。如何拋出ArrayIndexOutOfBoundsException?
我嘗試在聲明方法後添加throws ArrayIndexOutOfBoundsException
,但它不起作用。我該怎麼做呢?
throws
在方法定義中說該方法可以拋出異常。要真正把它扔在方法體中,使用throw new ArrayIndexOutOfBoundsException();
試試這個:
throw new ArrayIndexOutOfBoundsException("this is my exception for the condition");
基本上throws
關鍵字告訴我們,該方法可以拋出異常。如果你想拋出任何類型的異常,你需要調用該類型的構造函數。
throw new NullPointerException("Null Pointer Exception");
你的方法寫的聲明後:
private returnType methodName(CommunicationObject requestObject)
throws ArrayIndexOutOfBoundException {
}
如果你只是列出的功能是能夠拋出一個異常,但實際上從未拋出異常的功能,是不斷產生也不例外。
如果拋出異常但未列出可引發異常的函數,則可能會收到編譯器錯誤或有關未捕獲異常的警告。
你需要列出你的函數拋出一個ArrayIndexOutOfBoundsException並拋出異常在你的函數中的某處。
例如:
public ... myArrayFunction(...) throws ArrayIndexOutOfBoundsException {
.... // handle the array
if (some condition) {
throw new ArrayIndexOutOfBoundsException("Array Index Out of Bounds");
}
}
你有多少呢?在這裏粘貼一些代碼。 :) – HashimR 2012-03-29 04:19:14