This code is fine; what is it that you don't understand? When a method overrides another method, it is free to change the exception signature to make it more restrictive (it can't add new exceptions, but it can take some away.) The class AA has nothing whatsoever to do with the other two classes, so I'm not sure why you've included it, although there seems to be an extra close-brace at the end, which may indicate that something is missing.

Imagine there are two exception classes called Exception1 and Exception2 that descend from the Exception class. Given these two class definitions: class First { void test() throws Exception1, Exception2 { . . . } }

class Second extends First { void test() { . . . } } Create a class called Third that extends Second and defines a test() method. What exceptions can Third’s test() method throw? a.Exception1 b.Exception2 c.no checked exceptions d.any exceptions declared in the throws clause of the Third’s test() method

The answer to the above question is said as "C". But i feel the answer should be "a & b". I was intending to ask this question. I am extremely sorry for the above mistake. can you please explain why only c is correct and why not a and b. Thanks for the reply.

hiii.. i think it is pretty simple... the rule says that you cannot add new exceptions to method while overriding from parent class. and in this case the parent class of third class is second class and not the First Class.. so according to rules, one cannot add new exceptions.. so, as the method in Second class doesnot throw any exception... the dervied class also cannot throw any exception.. Thanks Amit

****************************<br />In 24 hrs Earth rotates once on its Axis.

Chandra Bairi
Ranch Hand

Joined: Sep 12, 2003
Posts: 152

posted Oct 14, 2003 00:30:00

0

Does that mean that the method in class Third cannot throw the exceptions exception1 and exception2 but can throw any other exceptions. One doubt, because I have the method in class Second overriding a method in class First will the original behaviour of the method in class First completely lost. if that is the case then the method in class Second should be able to throw any exceptions because it is just like any other method in the class Second. (or) but if the original behaviour of the method of Class First is not lost in class Second even after overriding then the method in class Second should be able to throw the same exceptions and if it can throw the exceptions then any classes subclassing that class should be able to throw it. Any comments will help me. Thanks

As I said, if you override a method, you change the exception declaration to make it more restrictive, but not less; i.e., you can throw fewer exceptions, but not more. So if Second declares that it throws no exceptions, then Third must also declare that it throws no exceptions.