(and it does indeed throw)
In my experience with Java, if you are throwing an Exception
in a method of a class that implements an interface, then the method you are overriding on the interface must also declare that it throws the 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's ByteBuffer.get()
doesn't declare that it throws any exceptions:
public abstract byte get();
But, its documentation says the following:
Throws:
BufferUnderflowException If the buffer's current position is not smaller than its limit
I then checked the implementation of HeapByteBuffer.get()
:
public byte get() {
return hb[ix(nextGetIndex())];
}
There we find nextGetIndex()
which is actually the method that would throw the BufferUnderflowException
, which by the way, also isn't declared with throws BufferUnderflowException
:
final int nextGetIndex() { // package-private
if (position >= limit)
throw new BufferUnderflowException();
return position++;
}
So, what am I missing here? If I try to declare a method that throws an Exception
, I get the error
Unhandled exception type Exception
Is this an IDE only error? I'm using Eclipse Juno. I would think if it was IDE only it would be a warning, but it is an actual error.
How can ByteBuffer.get() not declare its interface with throw BufferUnderflowException
, yet throw (and not catch it) one at the same time?
You only need to declare Checked Exception to be thrown in method, but not the Unchecked one. BufferUnderflowException
is an unchecked exception (it extends RuntimeException
), so it doesn't need to be declared to be thrown, and neither it needs to be handled.
Reference:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With