finally block without catch

  •  We know that try, catch and finally comes under Exception handling
  • And with that in java mutiple catch block is also possible
  • If  in a program mutiple exception  arises, and if that exception are of specific type,then we can use mutiple catch block also
  • Coming  to finally block,the finally block will execute when try/catch block leaves the execution means it is always executed when the try-catch ends in case of exception or not or  in other words it is  always  excuted whether the exception is  hanled or not
  • For example consider the code given below
public class HelloWorld{

     public static void main(String []args){

        int a=10;

        try {

            int k=10/0;
        }
        catch(ArithmeticException e){

            e.getMessage();

        }

        finally{

            System.out.println("Fianlly block is executed");

        }

        }

     }
  • Here in the main method we have an integer variable  a and it is initialized to 10
  • And in the next  case another variable k is declared and the value of this variable is optained by diving the value 10 by 0
  • So division by zero normally cause arithmetic exception
  • So this exception is handled by catch block
  • After that finally block will execute
  • So here the output will be
Fianlly block is executed
  • Suppose  if we rewrite the code like this
public class HelloWorld{

     public static void main(String []args){

        int a=10;

        try {

            int k=20/4;

            System.out.println(k);

        }
        catch(ArithmeticException e){

            
        }
        finally{

            System.out.println("Fianlly block is executed");

        }

        }

     }
  • Here no exception will occur becuase 20/4=5,So 5 will be printed,After that finally block will execute,So here the output will be

5

Fianlly block is executed

 
  • Next  we can use finally block  without catch,but we have to use try ,this is because finally block always executes when the try block exits
  • We can take the same program as  an example.in the above program if we remove catch
public class HelloWorld{

     public static void main(String []args){

        int a=10;

        try {
            int k=20/0;

            System.out.println(k);

        }
       
        finally{
            System.out.println("Fianlly block is executed");
        }
        }
     }
  • Here the output will be

Fianlly block is executed

Exception in thread "main" java.lang.ArithmeticException: / by zero at HelloWorld.main(HelloWorld.java:6)

 
  • Finally block is executed and then exception occurs 

    So we can use finally block without catch

     
Posted on by