• 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
  • Bear Bibeault
  • Jeanne Boyarsky
  • Tim Cooke
Sheriffs:
  • Knute Snortum
  • Junilu Lacar
  • Devaka Cooray
Saloon Keepers:
  • Ganesh Patekar
  • Tim Moores
  • Carey Brown
  • Stephan van Hulst
  • salvin francis
Bartenders:
  • Ron McLeod
  • Frits Walraven
  • Pete Letkeman

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

 
Ranch Hand
Posts: 1021
2
  • 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
 
author
Sheriff
Posts: 23604
138
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • 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
 
Greenhorn
Posts: 15
  • 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: 1021
2
  • 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
Boost this thread!