ceno980
ceno980

Reputation: 2011

Understanding exceptions in Java with interfaces

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.

Upvotes: 0

Views: 150

Answers (2)

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.

Upvotes: 5

Watachiaieto
Watachiaieto

Reputation: 422

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

Upvotes: 0

Related Questions