Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interface doesn't declare that it throws, yet documentation says it can throw

Tags:

java

exception

(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++;
}

Question

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?

like image 489
crush Avatar asked Dec 26 '22 21:12

crush


1 Answers

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:

  • JLS - Kinds and Causes of Exceptions
like image 69
Rohit Jain Avatar answered May 10 '23 14:05

Rohit Jain