Understanding exceptions in Java with interfaces

16
August 21, 2019, at 05:10 AM

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.

Answer 1

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.

Answer 2

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

READ ALSO
Intellij Project some files are not updating on compile

Intellij Project some files are not updating on compile

I am trying to compile an IntelliJ project, and have been working on it for over a month with no issuesToday I tried to compile and the changes I made in certain files did not make it into the compiled jar

47
Google Script MailApp - Setting Timer

Google Script MailApp - Setting Timer

Are there any possibilities that I can control how long it takes after a form has been submitted before it will send an email out?

51
Content overwritten on top of another when formula is applied to excel cell using Apache poi

Content overwritten on top of another when formula is applied to excel cell using Apache poi

I am getting an issue of content being overwritten on top of another ie old value and new values overlap after applying formula

31
Powershell as a java process on a unix system, output not displayed from cmdlet

Powershell as a java process on a unix system, output not displayed from cmdlet

I am writing an implementation for a powershell clientThis implementation is in java

46