Can any please explain why doe the following code does not compile. I understand that if a super class method throws an exception, the sub class method can throw only the exception thrown by the super class method or any subclass of the exception. Does'nt this apply to the constructors as well..
class Exp1 extends Exception{} class Exp2 extends Exp1{} class Base { Base() throws Exception { } public void amethod() throws Exception { } } class Child extends Base { Child() throws Exp1 { } public void amethod() throws Exp1 { } } Regards Vicky
Ana Abrantes
Ranch Hand
Joined: Sep 04, 2003
Posts: 43
posted
0
That's because constructors are not inherited so you can't override them. JVM will implicitly put super() in the constructor of your subclass and the super's constructor throws a wider exception than it's declared in the sub's constructor. You can fix this problem changing the throws in the Child cconstructor: Child() throws Exception{} or using try/catch inside it: Child() throws Exp1{ try{ super() } catch (Exception e){ // some code } } Hope I made it clear for you now! Ana
:roll:
Ana<p>SCJP 1.4
Jose Botella
Ranch Hand
Joined: Jul 03, 2001
Posts: 2120
posted
0
Constructors are not methods and they behave in a different way. A constructor in a derived class must declare at least the checked exceptions declared in the base class' constructor. Just because the super constructor is going to called and it is not possible to catch its exceptions inside the derived constructor: remember, super(...) or this(...) must be the the first sentence in a constructor body. try { super(...) } catch() {} is not possible. Besides that, a constructor in a derived class may declare exceptions unrelated to those at super class constructor, because they are inherent to the process the derived constructor carries out; which is unrelated to the process the base constructor performs.
SCJP2. Please Indent your code using UBB Code
Jose Botella
Ranch Hand
Joined: Jul 03, 2001
Posts: 2120
posted
0
Welcome to the Ranch Ana, please note that your code will not compile because super(); is not the first sentence in the constructor.
Barkat Mardhani
Ranch Hand
Joined: Aug 05, 2002
Posts: 787
posted
0
Hi Ana, I do not think this code will work: [c] Child() throws Exp1{ try{ super() } catch (Exception e){ // some code } } [/c] Because first statement in a constructor should be super or this if you need them. [ September 21, 2003: Message edited by: Barkat Mardhani ]
Maulin Vasavada
Ranch Hand
Joined: Nov 04, 2001
Posts: 1865
posted
0
Hi all, As Jose already pointed out we have to change declaration of the Child constructor as, Child() throws Exception rather than making it throw Exp1 type of the Exception... Regards Maulin