The 2 minute drill from page 69 SCJP kathy and bert book, says regarding Interfaces, that - "A legal nonabstract implementing class must not declare any new checked exceptions for an implementation method."
Can anybody please explain this , because , when I try the below given code in eclipse , it does not throw any errors . (Here I have tried to throw NullPointerException from testFunc whereas the interface function throws IllegalStateExc)
To elaborate on Joanne's post.
When you implement or override a method it must not violate its general contract. The general contract for testFunc says it throws IllegalStateExceptions. If you implement it in such a way that it does not throw an IllegalStateException, that is all right. But if you say it is going to throw another kind of Exception, that is wrong. It means you are saying the superclass method works under certain conditions but the subclass method doesn't.
Now the compiler doesn't check NullPointerExceptions (=NPE), so you can get away with it. This does not mean you can write this sort of thing:-That would constitute blatant violation of the general contract. But what happens if you are a bit careless in coding?… and mistakenly pass null to that set method? You will suffer an NPE, but not expect it. The idea of checked Exceptions is that they are expected. Unchecked Exceptions can occur when you don't expect them.It is only a matter of time before that code sets j to 0 and throws an ArithmeticException. Are you going to write throws ArithmeticException, NullPointerException, NoSuchElementException, OutOfMemoryError, OtherUncheckedException on every method heading?
That is why the compiler does not check every Exception. Although it is bad design to throw “new” unchecked Exceptions, you cannot check for every sort of unchecked Exception. With few exceptions (maybe NumberFormatException) you don't correct unchecked Exceptions by catching them: you correct them by altering the code, for example with this sort of changeThat is why the compiler will permit you to do anything with unchecked Exceptions. They are unchecked so it does not check them. The correct answer is simple:-
Don't declare unchecked Exceptions in a throws clause.
If you expect an unchecked Exception, however, you should declare it with a @throws tag in the documentation comments. Example here.