• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Devaka Cooray
  • Liutauras Vilda
  • Jeanne Boyarsky
  • Bear Bibeault
Sheriffs:
  • Paul Clapham
  • Knute Snortum
  • Rob Spoor
Saloon Keepers:
  • Tim Moores
  • Ron McLeod
  • Piet Souris
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • Tim Holloway
  • Frits Walraven
  • Ganesh Patekar

one doubt

 
Greenhorn
Posts: 23
  • 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;
}
}
}
 
Ranch Hand
Posts: 182
  • 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
 
Greenhorn
Posts: 9
  • 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;
}
}
}
 
Ranch Hand
Posts: 1282
  • 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 ]
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!