Page 1 of 1

About question com.enthuware.ets.scjp.v6.2.612

Posted: Mon Oct 13, 2014 9:01 am
by piotrkmiotczyk
I'm being mislinked here.
--------------------------in OO concepts (Exceptions and overriding) you wrote:-------
It can throw any exception as long as it is a subclass of any of the exceptions thrown by the overridden method. It can also be a subclass of RuntimeException. eg. If the base class A has: void m1() throws IOException then overriding method in class B can be : void m1() throws FileNotFoundException because FileNotFoundException is a subclass of IOException. The logic here is that if somebody is using class A like this:

Code: Select all

void someMethod( A a)
 {
    try {   a.m1() } catch(IOException) { }
 }
Now, if this method actually gets an object of class B (which is legal since B is a subclass of A) then the code should not fail. Therefore, any subclass of A must respect the contract established by class A. If B's m1() throws an exception that is not compatible with A's m1(), the above code will fail and so that exception will not be acceptable in the throws clause of B's m1().
--------------------------------------------------------------------------------------------------------------
Now this is a great explanation (from the practical side), but I don't know how it fits in with the fact that "Overriding method can throw any Runtime exception.". Which, if we pass to the method above will also break it, but the compiler of the a.m1() overriding code will not disallow this.

Re: About question com.enthuware.ets.scjp.v6.2.612

Posted: Mon Oct 13, 2014 7:08 pm
by admin
You seem to have misunderstood the meaning of "break" here. Runtime exceptions are not an issue here because it is understood that no one (i.e. the user of a component) can do anything about it. That is why it is not required to be caught or declared in the throws clause. The issue is with checked exceptions because these exceptions form a contract between the user and the provider of a component. When you throw an entirely new checked exception, the contract is violated. The user of a component has to explicitly make arrangements for checked exceptions (either using try/catch or by declaring in the throws clause) and adding a new checked exception requires the client code to be changed, which is what is meant by "breaking" the existing code.

HTH,
Paul.

Re: About question com.enthuware.ets.scjp.v6.2.612

Posted: Tue Oct 14, 2014 3:22 am
by piotrkmiotczyk
Thanks.

Re: About question com.enthuware.ets.scjp.v6.2.612

Posted: Mon Jan 12, 2015 4:41 am
by aitorbk
I disagree..

The overriding method can't throw an exception that the original one can.
The original can also throw subclasses of the declared exception..

It should be "declare to throw", not "throw".

Re: About question com.enthuware.ets.scjp.v6.2.612

Posted: Mon Jan 12, 2015 8:16 am
by admin
Which statement do you disagree with?