The interface does not declare that it quits, but the documentation says that it can quit

(and he really rushes)

In my experience with Java, if you throw an Exception on a class method that implements the interface, then the method that you override on the interface should also declare that it throws an Exception .

For example, consider the following minimal example:

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

However, I noticed that java.nio ByteBuffer.get() does not declare that it throws any exceptions:

 public abstract byte get(); 

But his documentation says the following:

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

Then I checked the implementation of HeapByteBuffer.get() :

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

Here we find nextGetIndex() , which is actually a method that throws a BufferUnderflowException , which, incidentally, is also not declared using throws BufferUnderflowException :

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

Question

So what am I missing here? If I try to declare a method that throws an Exception , I get an error

 Unhandled exception type Exception 

Is this just an IDE bug? I am using Eclipse Juno. I would have thought that if it were an IDE, that would be a warning, but this is a real mistake.

How does ByteBuffer.get () not declare its interface with throw BufferUnderflowException , but throw (and not catch it) at the same time?

+4
source share
1 answer

You only need to declare a checked exception, which will be selected by the method, but not removed. BufferUnderflowException is an unchecked exception (it extends RuntimeException ), so it does not need to be declared so that it is thrown, and it should not be handled.

Reference:

+10
source

Source: https://habr.com/ru/post/1500615/


All Articles