File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Exception Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Exception" Watch "Exception" New topic
Author

Exception

Chaitali Deshpande
Greenhorn

Joined: Jan 17, 2001
Posts: 26
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

Joined: Jan 15, 2001
Posts: 21
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).]


-LHS
Chaitali Deshpande
Greenhorn

Joined: Jan 17, 2001
Posts: 26
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

Joined: Jan 15, 2001
Posts: 52
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

Joined: Nov 22, 2000
Posts: 177
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

Joined: Nov 22, 2000
Posts: 177
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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Exception
 
Similar Threads
Constructor
where is the object created?
JavaCaps Mock Exams
Constructor exception doubt
finalize question