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

benfit of having try catch finaly instead of try catch as code after catch will run in either case

 
Monica Shiralkar
Ranch Hand
Posts: 825
1
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
if we have try catch finally , then instead of having finally if we write the code which should be in finally block without a finally block after catch, then also it will be executed in either case. So what is the benfit we got by using try catch finally instead of try catch.

thanks
 
Henry Wong
author
Marshal
Pie
Posts: 20834
75
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Monica. Shiralkar wrote:if we have try catch finally , then instead of having finally if we write the code which should be in finally block without a finally block after catch, then also it will be executed in either case. So what is the benfit we got by using try catch finally instead of try catch.


Basically, your premise is incorrect. The finally block will execute, even if exceptions are thrown that are not caught (in cases where some exceptions are caught, but not others), or a return is executed in the try or catch blocks (which normally, mean that the code after the try-catch will not run). The finally block run when the try-catch completes, regardless of how it completes.

Henry
 
ashish bassii
Greenhorn
Posts: 15
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The code mentioned in finally block will execute even if the exception thrown is not handled by any of the exception blocks, so if you have try block, a catch block for ArithmeticException, and a finally block.. but the exception you actually got in try block is IOExcepton, the finally block will still execute, but the code after catch block wont
 
Monica Shiralkar
Ranch Hand
Posts: 825
1
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic