4

(它确实抛出)

根据我使用 Java 的经验,如果您Exception在实现接口的类的方法中抛出一个,那么您在接口上覆盖的方法也必须声明它抛出Exception.

例如,考虑以下最小示例:

public interface MyInterface {
    void doSomething() throws IOException;
}


public class MyClass implements MyInterface {
    @Override
    public void doSomething() throws IOException {
        throw new IOException();
    }
}

但是,我注意到 java.nioByteBuffer.get()没有声明它抛出任何异常:

public abstract byte get();

但是,它的文档说如下:

Throws:
    BufferUnderflowException If the buffer's current position is not smaller than its limit

然后我检查了以下的实现HeapByteBuffer.get()

public byte get() {
    return hb[ix(nextGetIndex())];
}

在那里我们发现nextGetIndex()which 实际上是抛出 ​​的方法,BufferUnderflowException顺便说一下,它也没有用 声明throws BufferUnderflowException

final int nextGetIndex() {                          // package-private
    if (position >= limit)
        throw new BufferUnderflowException();
    return position++;
}

问题

那么,我在这里缺少什么?如果我尝试声明一个抛出 的方法Exception,我会收到错误

Unhandled exception type Exception

这是仅 IDE 的错误吗?我正在使用 Eclipse Juno。我认为如果它只是 IDE,那将是一个警告,但这是一个实际错误。

ByteBuffer.get() 如何不声明它的接口throw BufferUnderflowException,但同时抛出(而不是捕获)一个?

4

1 回答 1

10

您只需要声明要在方法中抛出的 Checked Exception,而不是 Unchecked 。BufferUnderflowException是一个未经检查的异常(它 extends RuntimeException),所以它不需要被声明为被抛出,也不需要被处理。

参考:

于 2013-09-04T21:18:45.170 回答