【发布时间】:2013-10-12 04:17:42
【问题描述】:
我试图弄清楚Java中方法签名中的抛出和抛出语句之间的区别。 方法签名中的抛出如下:
public void aMethod() throws IOException{
FileReader f = new FileReader("notExist.txt");
}
抛出语句如下:
public void bMethod() {
throw new IOException();
}
根据我的理解,方法签名中的throws 是一个通知,该方法可能会抛出这样的异常。 throw 语句是在相应情况下实际抛出创建的对象。
从这个意义上说,如果方法中存在 throw 语句,则方法签名中的 throws 应始终出现。
但是,以下代码似乎没有这样做。代码来自图书馆。我的问题是为什么会这样?我对概念的理解有误吗?
这段代码是 java.util.linkedList 的副本。 @作者乔什·布洛赫
/**
* 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 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(); throw e。看到不同?throw抛出,new创建一个实例。