In the book "Oracle Certified Professional Java SE 7 Programmer Exams 1Z0-804 and 1Z0-805 A Comprehensive OCPJP 7 Certification Guide" by S G Ganesh and Tushar Sharma, it's stated
"if a method is declared in 2 or more interfaces, and if that method declares to throw different exceptions in the throws clause, the implementation should list all these exceptions" (page 347)
Well, then I've tried this
public interface I1 {
public void x() throws I1Exception;
}
public interface I2 {
public void x() throws I2Exception;
}
public class I1Exception extends Exception {
}
public class I2Exception extends Exception {
}
public class Sample implements I1, I2{
@Override
public void x() throws I2Exception {
throw new I2Exception();
}
@Override
public void x() throws I1Exception {
throw new I1Exception();
}
}
Of course, the exception is not part of the method signature, so the compiler complains that the second method is duplicated.
On the other hand
@Override
public void x() throws I1Exception, I2Exception {
throw new I1Exception();
}
Is not compatible with both interfaces because it declares more checked exceptions than any one of the methods of each interface, taken separately.
This means that I don't understood what the book says or does that mean the book statement is innacurate?
After giving it a second thought, I think the intention of the book was to say that you have to satisfy both interfaces at the same time.
So the method should throw (roughly speaking) an intersection of sets of exceptions of both methods. If these sets don't intersect then the method can't throw anything. So this:
@Override
public void x() {
}
Is OK for both interfaces.
(It's a bit more complicated because of inheritance, but you get the idea.)
So from my point of view
"if a method is declared in 2 or more interfaces, and if that method declares to throw different exceptions in the throws clause, the implementation should list all these exceptions" (page 347)
can't be correct because it does not work in practice. You (in most cases) can't list all of these exceptions in an implementation. There are exceptions like unchecked exceptions or identical/compatible sets of exceptions.
However I could not find normative reference in JLS for this.
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