0

I have the following code which has two interfaces which have two methods of the same name. However each method throws a different type of Exception.

public interface xyz {
void abc() throws IOException;
}
public interface qrs {
void abc() throws FileNotFoundException;
}
public class Implementation implements xyz, qrs {
// insert code
{ /*implementation*/ }
}

I know that in inheritance if a subclass method overrides a superclass method, a subclass's throw clause can contain a subset of a superclass's throws clause and that it must not throw more exceptions. However, I am not sure how exceptions are dealt with in interfaces.

For the implementation of the function abc() in the class Implementation, can this method throw both of the exceptions or just one? For example, is the following method valid?

public void abc() throws FileNotFoundException, IOException

Any insights are appreciated.

1
  • 2
    Why don't you try? Commented Aug 20, 2019 at 2:32

2 Answers 2

5

A class that implements an interface must satisfy all of the requirements of that interface. One requirement is a negative requirement--a method must not throw any checked exceptions except those declared with a throws clause on that interface.

FileNotFoundException is a specific kind (subclass) of IOException, so if your Implementation class declares void abc() throws FileNotFoundException, it satisfies the requirements of both qrs (which permits only that specific exception) and xyz (which permits any kind of IOException). The inverse is not true, however; if it says that it throws IOException, it doesn't meet the contract of qrs.

Sign up to request clarification or add additional context in comments.

2 Comments

Just to clarify, is the contract of qrs the fact that if an implementing class has the method abc() it must throw the FileNotFoundException?
@ceno980 No, that's what I meant by negative requirement; the implementing class may throw FileNotFoundException, but it must not throw any other checked exceptions. An implementation that declared no throws clause at all would be fine.
0

They do not have to throw the exceptions of an interface. Your function may not throw exceptions that were not in the interface.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.