(它确实扔了)
根据我使用Java的经验,如果你Exception在一个实现接口的类的方法中抛出一个,那么你在接口上覆盖的方法也必须声明它抛出了Exception.
例如,请考虑以下最小示例:
public interface MyInterface {
void doSomething() throws IOException;
}
public class MyClass implements MyInterface {
@Override
public void doSomething() throws IOException {
throw new IOException();
}
}
Run Code Online (Sandbox Code Playgroud)
但是,我注意到java.nio ByteBuffer.get()没有声明它抛出任何异常:
public abstract byte get();
Run Code Online (Sandbox Code Playgroud)
但是,它的文档说明如下:
Throws:
BufferUnderflowException If the buffer's current position is not smaller than its limit
Run Code Online (Sandbox Code Playgroud)
然后我检查了执行HeapByteBuffer.get():
public byte get() {
return hb[ix(nextGetIndex())];
}
Run Code Online (Sandbox Code Playgroud)
在那里我们发现nextGetIndex()哪个实际上是抛出的方法,BufferUnderflowException顺便说一句,也没有声明throws BufferUnderflowException:
final int nextGetIndex() { // package-private
if (position >= limit)
throw new BufferUnderflowException();
return position++;
}
Run Code Online (Sandbox Code Playgroud)
那么,我在这里错过了什么?如果我尝试声明抛出一个方法Exception,我会得到错误
Unhandled exception type Exception
Run Code Online (Sandbox Code Playgroud)
这是IDE唯一的错误吗?我正在使用Eclipse Juno.我认为如果它只是IDE它会是一个警告,但它是一个实际的错误.
ByteBuffer.get()怎么不声明它的接口throw BufferUnderflowException,但同时抛出(而不是捕获它)?
Roh*_*ain 10
您只需要在方法中声明Checked Exception,而不是Unchecked.BufferUnderflowException是一个未经检查的异常(它扩展RuntimeException),因此不需要声明它被抛出,也不需要处理它.
参考:
| 归档时间: |
|
| 查看次数: |
98 次 |
| 最近记录: |