I am trying to make it clear of the difference between Throws in method signature and Throw Statements in Java.
Throws in method signature is as following:
public void aMethod() throws IOException{
FileReader f = new FileReader("notExist.txt");
}
Throw Statements is as following:
public void bMethod() {
throw new IOException();
}
From my understanding, a throws
in method signature is a notification that the method may throw such an exception. throw
statement is what actually throw a created object under according circumstances.
In that sense, throws in method signature should always appear if there exist a throw statement in the method.
However, the following code doesn't seem doing so. The code is from the library. My question is why it is happening? Am I understanding the concepts wrong?
This piece of code is a copy from java.util.linkedList. @author Josh Bloch
/**
* 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;
}
Update on the answer:
update 1 : is above code the same as the following?
// 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;
}
update 2 : For checked exception. Do I need to have "throws" in the signature? Yes.
// has to throw checked exception otherwise compile error
public String abc() throws IOException{
throw new IOException();
}
question from:
https://stackoverflow.com/questions/19193540/difference-between-throws-in-method-signature-and-throw-statements-in-java 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…