File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

doubt about output.

 
Deep Chand
Ranch Hand
Posts: 133
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
In the following piece of code, if you invoke 'java Test' then it throws
StackOverFlowError because of the object creation in the constructor itself. However, the output is 'Exception caught' followed by lots of 'in cons'. My doubt is how come the execution reaches the line 2. Any ideas?
Thanks,
Deep
public class Parcel {
Parcel() {
try{
Parcel p = new Parcel(); // line 1
System.out.println("in cons"); // line 2
}
catch (Error e) {
System.out.println("Exception caught");
}
}
}
class Test {

public static void main(String [] args) {
Parcel p = new Parcel();
}
 
Pradeep bhatt
Ranch Hand
Posts: 8927
Firefox Browser Java Spring
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When memory is not sufficient OutOfMemoryError is thrown and it is caught.
All other objects in the recursive list will be creted and so system.out statement.
 
Alton Hernandez
Ranch Hand
Posts: 443
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Deep,
The error that caused the 'Exception caught' message was actually thrown by the last call to the constructor Parcel(). The message 'in cons' was created by the objects before that.
If you look at the constructor of Parcel(), it is calling itself. So, the first call will not return unless the 2nd call returns, and so on. In short, you have an endless loop.
The message 'in cons' will be printed only after the call to Parcel() returns. So, the first call is the last one to exit, and the last call is the first one to exit the try clause. The last call returns an error so it is the first one to print the message 'Exception caught'.
[ September 04, 2003: Message edited by: Alton Hernandez ]
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic