Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Exception

 
Chaitali Deshpande
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi
I have problem with the following code
import java.io.*;
class A {
A() throws Exception {
System.out.prinln ("Executing class A constructor");
throw new IOException();
}
}
public class B extends A {
B() throws Exception{
System.out.prinln ("Executing class B constructor");
}
public static void main ( String args[] ) {
try {
A a = new B();
} catch ( Exception e) {
System.out.println( e.getMessage() );
}
}
}
the o/p is
Executing class A constructor
null
My problem is why do i get null in o/p
Thanks in advance
 
Son Le
Greenhorn
Posts: 21
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Chaitali,
During the construction of an instance of B, exception is thrown from A() constructor. (B() construtor calls default constructor in A()) Since you don't specify the message, the default is null.
Try the following code for clarification

"OK" will print at the end.
SonLe
[This message has been edited by Son Le (edited January 17, 2001).]
[This message has been edited by Son Le (edited January 17, 2001).]
 
Chaitali Deshpande
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank You.
I have one more Question regarding the above program
Is there any other way by which derived class can
handle exceptions thrown by constructor of parent class
 
Wong KK
Ranch Hand
Posts: 52
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can anyone tell me why the above code runs A's constructor instead of B's?
A a = new B();
For me, it should be interpreted as new a B instance and then implicit cast it to an A instance. So, B's constructor should be run.
Thx. and Regards.
KK.
 
Bob Moranski
Ranch Hand
Posts: 177
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It has to do with "constructor chaining". When you call the no args constructor of a subclass, an implicit super() is called within the subclass' constructor.
 
Bob Moranski
Ranch Hand
Posts: 177
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It has to do with "constructor chaining". When you call the no args constructor of a subclass, an implicit super() is called within the subclass' constructor.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic