Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overriding Java interfaces with new checked exceptions

Suppose in Java, I'm using a preexisting interface that is rather general

public interface Generator {
    public String generate();
}

and I have my own class

public class FromFileGenerator implements Generator {
    ...
    public String generate() throws FileNotFoundException {
        String output = //read from some file
        return file;
    }
}

The Java compiler yells at me because the implementation of generate() contains an exception not specified in the original signature (FileNotFoundException). However, clearly the exception does not belong in the interface, but it also cannot be neglected in the implementing class. How can this be resolved without simply failing silently?

like image 733
donnyton Avatar asked Nov 27 '22 17:11

donnyton


1 Answers

You cannot add a checked exception to the declaration of a method that hides, overrides, or implements another method. You will need to catch the exception within the method and do something else with it (such as return null, or throw an unchecked exception, possibly wrapping the checked exception).

From the Java Language Specification, §8.4.8.3:

A method that overrides or hides another method, including methods that implement abstract methods defined in interfaces, may not be declared to throw more checked exceptions than the overridden or hidden method.

like image 144
Ted Hopp Avatar answered Dec 04 '22 10:12

Ted Hopp