• 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
  • Liutauras Vilda
  • Tim Cooke
  • Jeanne Boyarsky
  • Bear Bibeault
Sheriffs:
  • Knute Snortum
  • paul wheaton
  • Devaka Cooray
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Ron McLeod
  • Piet Souris
  • Ganesh Patekar
Bartenders:
  • Tim Holloway
  • Carey Brown
  • salvin francis

why this is compiling fine?

 
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?
 
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.
 
author
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
 
This parrot is no more. It has ceased to be. Now it's a tiny ad:
create, convert, edit or print DOC and DOCX in Java
https://products.aspose.com/words/java
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!