我想清除中的方法簽名和中的拋出拋出Java中的語句。 拋出在方法簽名如下:方法簽名中的拋出和Java中的拋出語句之間的區別
public void aMethod() throws IOException{
FileReader f = new FileReader("notExist.txt");
}
throw語句是如下:
public void bMethod() {
throw new IOException();
}
從我的理解,在方法簽名throws
是,該方法可能會拋出這樣的異常的通知。語句是在相應的情況下實際拋出創建的對象的語句。 從這個意義上說,在方法簽名中拋出應該總是出現,如果在方法中存在拋出語句。
但是,下面的代碼似乎並沒有這樣做。代碼來自庫。我的問題是爲什麼它發生?我是否理解錯誤的概念?
這段代碼是java.util.linkedList的副本。 @author對答案喬希布洛赫
/**
* Returns the first element in this list.
*
* @return the first element in this list
* @throws NoSuchElementException if this list is empty
*/
public E getFirst() {
final Node<E> f = first;
if (f == null)
throw new NoSuchElementException();
return f.item;
}
更新:
更新1:是上面的代碼相同,以下?
// as far as I know, it is the same as without throws
public E getFirst() throws NoSuchElementException {
final Node<E> f = first;
if (f == null)
throw new NoSuchElementException();
return f.item;
}
更新2:對於檢查的異常。我需要在簽名中「扔」嗎?是。
// has to throw checked exception otherwise compile error
public String abc() throws IOException{
throw new IOException();
}
只是一個小小的更正:'throw'語句不會創建可拋出的對象;它只是拋出一個已經創建的對象。這是創建對象的'new'關鍵字。把'throw new MyException()'看作'throw(new MyException())'。你也可以有'MyException e = new MyException();扔e'。看到不同? 'throw'拋出,'new'創建一個實例。 –