Java Finally

Java Finally

Java Finally

Finally is a block used along with try catch statement. Finally block is always executed whether you have exception or not. In this tutorial, we will discuss about finally block and how is it useful.

Java Finally



But before let’s discuss about finally block in java.


Finally Block

Finally block is used with try catch statement, finally block is always executed. You can use either catch or finally block along with try block. You can use finally block to release the stream, close the connection because it is always executed whether you have any exception or not.

Some important things about finally block.


  1. Finally block is always executed.
  2. Finally is reserved keyword in java.
  3. Finally block can only be used with try catch statement.
  4. A try statement can only have finally block.
  5. You can have only single finally block and number of catch block.
  6. Finally will not be executed if you terminate the execution of the program before the finally block.


Basic syntax

try {
     // Code
} catch (Exception e) {
     // Exception handling
} finally {
     // Code which you want to be executed inside finally block.
}

A basic example on finally block.


public class FinallyExample {

  public static void main(String arg[]) {
 
    System.out.println("Before try block.");
    try {
       System.out.println("Inside try block.");
       int a = 10/0;
    } catch (Exception e) {
       System.out.println("Exception occured : " + e.getMessage());
    } finally {
       System.out.println("Finally block executed.");
    }
  }
}

Output

Before try block.
Inside try block.
Exception occured : / by zero
Finally block executed.

Related Post

Leave a Reply

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