Tutorials

Java Exception Handling


finally block


finally block is followed by either try block or try-catch block.

 

finally block contains important clean up codes like closing open connections, open streams, etc. that needs to be closed before the try block execution ends.

Points to note:

  • finally block will always get executed irrespective of whether exception is caught or not.
  • Each try block can contain only one finally block. However multiple catch block is allowed with try.
  • finally block should be declared at the end after all the catch block has been declared. If you declare finally before the catch block then the result would be compilation error.
  • In case of nested try block, each nested try can have their own finally block.

Syntax of try-catch-finally block


     try{
         Statement 1;
     }catch(ArithmeticException e){
          //catch body
     }catch(ArrayIndexOutOfBoundsException e){
         //catch body
     }finally{
        //finally body
     }

Syntax of try-finally block


      try{
          Statement 1;
             ……
          Statement N;
      }finally{
          //finally body
      }

Examplejava finally example

package exceptionHandling;

public class MultipleCatchBlock {

      public static void main(String[] args) {

            try{

                  int a = 20, b = 0;
                  int div = a/b;


                  int arr[] = {1,2,3,4,5};
                  System.out.println(arr[10]);

            }catch(ArithmeticException e){

                  System.out.println("Division by 0 not allowed");

            }catch(ArrayIndexOutOfBoundsException e){

                  System.out.println("Given index doesnot exist in array");

            }catch(Exception e){

                  System.out.println("Some exception occured");

            }finally{

                  System.out.println("finally always executed");
            }
      }
}

OUTPUT:

Division by 0 not allowed
finally always executed
 

Example: finally executes even if no exception is caught.

 

public class HelloWorld {

      public static void main(String[] args) {
         
            try{

            System.out.println("I will learn java on tutorialsinhand.com");

            }catch(Exception e){

                  System.out.println("Exception occured");

            }finally{

                  System.out.println("finally block always executed");

            }
      }
}

OUTPUT:

I will learn java on tutorialsinhand.com
finally block always executed


Please Share this page
Views : 55