What is finally block in Java?

What is finally block in Java?

What is finally block in Java?

What is finally block in Java?
  • It is not recommended to maintain cleanup code inside try block because there is no guarantee for the execution of every statement inside the try block.
  • It is not recommended to maintain cleanup code inside the catch block. Because if there is no exception then catch block won’t be executed.
  • Hence we required someplace to maintain cleanup code which should be executed always irrespective of whether exception raised or not raised or whether to handle or not handle.
  • Such type of best is nothing but finally block.
  • The finally block is a key tool for preventing resource leaks. When closing a file or otherwise recovering resources, place the code in a finally block to ensure that resource is always recovered. But finally is useful for more than just exception handling — it allows the programmer to avoid having cleanup code accidentally bypassed by a return, continue, or break. Putting cleanup code in a finally block is always a good practice, even when no exceptions are anticipated.
  • Hence the main objective of finally block is to maintain clean up code
try{
  //risky code
}
catch(Exception e){
  //Handling code
}
finally{
  //clean up code
}
  •  A finally block must be associated with a try block, you cannot use finally without a try block. You should place those statements in this block that must be executed always.
  • Finally block is optional, if you place a finally block then it will always run after the execution of try block.
  • In normal case when there is no exception in try block then the final block is executed after the try block. However, if an exception occurred then the catch block is executed before finally block.
  • An exception in the finally block, behaves exactly like any other exception.

Leave a Reply

Your email address will not be published. Required fields are marked *

*