• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

What is the exact use of a finally block in exception handling?

 
rakesh kadulkar
Ranch Hand
Posts: 115
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi

I want to know the exact scenario where I can use a finally block in exception handling? Please explain with an example.
 
Campbell Ritchie
Sheriff
Pie
Posts: 50196
79
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Java™ Tutorials.
 
Sebastian Janisch
Ranch Hand
Posts: 1183
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The most popular example is a database connection. The finally block WILL run even if there are tons of exceptions happening in your try block. Since you want to close your database connection cleanly, this is to be done in the finally block, whether there have exceptions been raised or not.
 
Muhammad Khojaye
Ranch Hand
Posts: 449
IntelliJ IDE Java Scala
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Key benefits of using finally have already listed.

Suppose you have a code

Now, many times the catch block re throw an exception and goes out of the current function. In that case the function "funcMustExecute" will not execute. In order to ensure that you function get execute you should write it in the finally block.
Hope it helps.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic