• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

why this is compiling fine?

 
manu sinha
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
public class Test{
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;
}
}
}

This compiles fine and prints 3.Why?
 
Sanju Thomas
Ranch Hand
Posts: 243
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What is wrong with this code. Even though you are throwing an Exception, Your finally block will return 3 back to the calling method. Then there is no fault with the code.
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The return in the finally block *always* gets executed, even you throw an exception earlier.

That's, of course, very bad style and actually should *never ever* be done. That is, you should never have something returned from or thrown in a finally block.

The java compiler should actually give you a warning for the above code.
 
manu sinha
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
THANK YOU
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic