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

one doubt

 
Rippon Jalali
Greenhorn
Posts: 23
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The problem in the code below is that catch clause in the called method rethrows exception,and main method neither handles nor declares the exception.So shouldn't it give compiler error?but it isgiving answer 3.
Can any body explain.

public class Test3{
public static void main(String args[]){
System.out.println(method());
}
public static int method(){
try{
throw new Exception();
}
catch(Exception e){
throw new Exception();
}
finally{
return 3;
}
}
}
 
Ajay Singh
Ranch Hand
Posts: 182
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
because you have finally block. whether there is exception or not, finally gets executed and it would always return 3
 
Crace Selvage
Greenhorn
Posts: 9
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Once an exception is discovered your code will search for an appropriate catch block. Once it enters a catch block, it will never return back to the method, even if handled properly. Once the catch block is done flow will proceed to the finally block.


public class Test3{
public static void main(String args[]){
System.out.println(method());
}
public static int method(){
try{
throw new Exception();
}
catch(Exception e){
throw new Exception();
}
finally{
return 3;
}
}
}
 
Nicholas Jordan
Ranch Hand
Posts: 1282
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Rippon Jalali:
The problem in the code below is that catch clause in the called method rethrows exception,and main method neither handles nor declares the exception.So shouldn't it give compiler error? but it is giving answer 3.
Can any body explain.


The compiler gave me an error when I did not declare a throws for main.

Additionally, you throw a new exception - not the one passed into the catch() ....

[message edit: finally executes no matter what, thus explains the printing of 3]

Usually what I do is just recode it each way and see what the compiler has to say about it.

[ January 07, 2007: Message edited by: Nicholas Jordan ]
[ June 09, 2007: Message edited by: Nicholas Jordan ]
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic