gpt4 book ai didi

java - 接口(interface)没有声明它抛出,但文档说它可以抛出

转载 作者:搜寻专家 更新时间:2023-11-01 01:26:54 24 4
gpt4 key购买 nike

(它确实抛出)

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

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

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


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

但是,我注意到 java.nio 的 ByteBuffer.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()这实际上是会抛出 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 的接口(interface),而是同时抛出(而不捕获)一个?

最佳答案

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

引用:

关于java - 接口(interface)没有声明它抛出,但文档说它可以抛出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18623948/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com