Flow Control in try-catch-finally in JAVA

Try-Catch-Finally

Try Block

  • The statements that can generate an exception must be placed in this block.
  • If exception occurs then catch block is executed and then finally block is executed
  • If exception occurs but no matching catch block is found then the control will go directly to the finally block that is after try block the catch block is not executed and the execution of the program goes directly to the finally block.
  • If no exception occurs then the control will go directly to the finally block that is after try block the catch block is not executed and the execution of the program goes directly to the finally block.

Catch Block

  • The exception thrown by the try block are caught by the catch block.
  • The catch block will only get executed if the exception occurred in try block matches with the exception in catch block.

Finally Block

  • Finally Block is always executed irrespective of whether an exception occurs or not.
  • This is an optional block i.e we can have a try-catch block without a finally block.

Program(Save as DivException.java)

Handling divide by zero exception using try catch finally.

import java.util.*;
public class DivException

{

    public static void main(String []args){
    Scanner sc = new Scanner(System.in);
    int num,den;
    double ans;
    System.out.println("Enter numerator");

    num = sc.nextInt();
    System.out.println("Enter denominator");

    den = sc.nextInt();
        try{
            ans = num/den ;
            System.out.println("Division("+num+"/"+den+") = "+ans);
        }
        catch(ArithmeticException e){
            System.out.println("Exception occurred!");
        }
        finally{
            System.out.println("Finally block executed");
        }
    }
}

Output

Enter numerator
11
Enter denominator
0
Exception occurred!
Finally block executed

In the above program, we can see that the part which could generate an exception(ans = num/den) is inside the try block. Notice that the print statement inside the try block is not executed as whenever an exception in try block occurs the statements after that inside the try block are not executed.

Also notice that the finally block is always executed whether an exception occurs or not, as practice you can enter different values in the denominator or modify code to understand better.

Multiple Try Catch Block

  • You must be thinking what if we have more than one exception in our application(which is quite common), then how should we handle them, hence the use of multiple try catch block.
  • When multiple exceptions are to be caught, we must use multiple try catch block.
  • All statements in our code that can generate an exception must be kept in a single try block and multiple catch blocks for handling exceptions indicated by its arguments.

Program(MultipleTry.java)

Handling divide by zero exception as well as InputMisMatch exception.

import java.util.*;
public class MultipleTry{

    public static void main(String []args){

        try{
            Scanner sc = new Scanner(System.in);
            int num,den;
            double ans;
            System.out.println("Enter numerator");
            num = sc.nextInt();
            System.out.println("Enter denominator"); 
            den = sc.nextInt();

            ans = num/den ;
            System.out.println("Division("+num+"/"+den+") = "+ans);
        }        
        catch(ArithmeticException e){
            System.out.println("Arithmetic Exception occurred!");
        }
        catch(InputMismatchException e){
            System.out.println("InputMismatchException occurred!");
        }

    }
}

Output

Enter numerator
11
Enter denominator
a
InputMismatchException occurred!

From the above program you can see that we can now handle multiple exceptions.

Nested Try Catch Block

  • When a try catch block is present in another try block then it is called nested try catch block.
  • Each time a try block does not have a catch handler for a particular exception, then the catch blocks of parent try block are inspected for that exception, if match is found that that catch block executes.
  • If neither catch block nor parent catch block handles exception then the system generated message would be shown for the exception.

Program(Save as NestedTry.java)

import java.util.*;
public class NestedTry{

    public static void main(String []args){

        try{ //1st Try Block
            try{ //2nd Try Block
                Scanner sc = new Scanner(System.in);
                int num,den;
                double ans;
                System.out.println("Enter numerator");
                num = sc.nextInt();
                System.out.println("Enter denominator"); 
                den = sc.nextInt(); 

                try{ //3rd Try Block
                    ans = num/den ;
                    System.out.println("Division("+num+"/"+den+") = "+ans);
                }

                catch(ArithmeticException e){ //3rd Catch Block
                    System.out.println("Arithmetic Exception occurred!...Inner Catch");
                }
                finally{
                    System.out.println("3rd FINALLY!");
                }
            }
            catch(ArrayIndexOutOfBoundsException e){ //2nd Catch Block
                System.out.println("InputMismatchException occurred!");
            }
            finally{
                System.out.println("2nd FINALLY!");
            }
        }
        catch(Exception e){ //1st catch
            System.out.println(e.toString()+" occurred!!!");
        }
        finally{
            System.out.println("1st FINALLY!");
        }

    }
}

Output

Enter numerator
11
Enter denominator
a
2nd FINALLY!
java.util.InputMismatchException occurred!!!
1st FINALLY!

In the above program we can see that, 1st and 2nd try blocks are executed and the 3rd try block is skipped. The 3rd and 2nd catch blocks are not executed as the exception generated doesn't match, while the 2nd finally block is executed as the 2nd try block was executed. The first catch block handles all the exceptions which are not caught by the 2nd and 3rd catch block. We can also see that that another way to print an exception is to use toString() method.

Share Me!