finally block in java Exception handling

This “finally block in java Exception handling” page providing introduction to finally block, how to use finally block to close statements in java exception handling process.



  • A block of instructions.
  • Used to release a resource(File, IO-device, database, server..) in Exception handling.
  • Mostly used in case of Checked exceptions handling.
  • finally block executes whether or not an Exception has raised in the try-block.
  • finally block executes in case of abnormal termination of program also.


Blocks – Usage :

  1. try-block : Handling Exception.
  2. catch block : Avoids abnormal termination.
  3. finally block : Resource releasing code / working with Checked Exception.


Note the followings…

  • try-block cannot be present without either catch-block or finally-block.
    • if try-catch is present, finally-block is optional
    • if try-finally is present, catch-block is optional
  • finally block gets execute in case of Abnormal termination of program also.
  • The order of 3 block as try-catch-finally respectively.
  • No other statement is allowed in between try-catch-finally.


The following program describes how finally-block executes in all the situations.


Following program explains how finally block executes in case of abnormal termination of program.


Program explains how to use finally block to close a resource(file).

Closing File using Finally Block


  • We can handle NullPointerException as follows in case of no file.
  • Following program explains clearly how to handle NullPointerException while releasing File.


Share this