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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With