GeeCON Prague 2014*
The moose likes Beginning Java and the fly likes one doubt Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » Beginning Java
Bookmark "one doubt " Watch "one doubt " New topic
Author

one doubt

Rippon Jalali
Greenhorn

Joined: Aug 25, 2006
Posts: 23
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

Joined: Dec 13, 2006
Posts: 182
because you have finally block. whether there is exception or not, finally gets executed and it would always return 3
Crace Selvage
Greenhorn

Joined: Jan 14, 2005
Posts: 9
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

Joined: Sep 17, 2006
Posts: 1282
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 ]

"The differential equations that describe dynamic interactions of power generators are similar to that of the gravitational interplay among celestial bodies, which is chaotic in nature."
 
GeeCON Prague 2014
 
subject: one doubt