Java Advanced Topics and Techniques

Try, Catch and Finally in Java

Try, Catch and Finally in Java

Introduction

While executing a Code of any programming language, there can be factors that obstruct the code execution. These are called exceptions. Thus, an exception is an anomaly or run-time error that hinders the normal flow of the program. In this article, we will see how we can handle the exception and maintain the flow control of java programs using the concept of Try Catch Finally in Java.

In normal conditions, the compiler executes the code in a top-down manner. But, whenever an exception is raised in any piece of code, the flow of the program is controlled by using the Try, Catch and Finally Block so that the program can be executed successfully. Exception Handling is one of the most important features of Java Programming which allows the developers to prevent the abrupt or abnormal termination of the program due to exceptions.

For example, suppose you take a number and try to divide it by zero.

public class ClassInterFace{
    public static void main(String arg[]){
        int n =10;
        System.out.println(n/0);
    }
}

You will encounter the following Arithmetic Exception:

Exception in thread "main" java.lang.ArithmeticException: / by zeroat ClassInterFace.main(ClassInterFace.java:4)

write your code here: Coding Playground

Thus, the Try Catch Finally in Java is used to handle the piece of code which may cause an exception. For example in the above case, the try-catch in java can be used as:

public class ClassInterFace{
    public static void main(String arg[]){
        try{
            int n =10;
              System.out.println(n/0);
        }
        catch(Exception e){
            System.out.println(" Following exception occured\n" +e );
        }
    }
}

Output:

Following exception occured
java.lang.ArithmeticException: / by zero

write your code here: Coding Playground

Let’s see the various use cases of flow control using the Try, Catch and Finally block in Java code.

The Try Catch and Finally can be used in the following ways:

  • Try-Catch Block: A try block is used with one or multiple catch blocks.
  • Try-Catch Finally Block: A try block is used with the Catch and Finally blocks.
  • Try-Finally Block: A Try block is used with the Finally block.

Following are the important points about the try-catch-finally blocks:

  • There can be only one Finally Block.
  • Try block cannot be used alone. It must have either a Catch block or a Finally block.
  • You cannot have multiple try blocks with a single catch block in Java.
  • One try block can be followed by multiple catch blocks.

Now, let’s see the various cases of control flow using the Try Catch Finally in Java.

Control Flow using Try-Catch or Try-Catch-Finally Block

Case 1

Exception is raised inside the try block and handled in the catch block.

In this case, if the exception occurs in the try block, the control immediately passes to the catch block without the execution of the remaining try block. If there is a finally block, then control passes to the finally block after the catch block. The implementation of this case of try catch finally in java is given below:

public class ClassInterFace{
    public static void main(String arg[]){
     
        try{
            System.out.print(10/0);

            System.out.print("Dummy Statement");//this does not executes
        }
        catch(Exception c){
            System.out.println("Exception caught");

        }
        finally{
            System.out.println("Final block executed");

        }
    }
}

Output:

Exception caught
Final block executed

write your code here: Coding Playground

Case 2

Exception is raised inside the try block and not handled in the catch block.

In this case, if the exception occurred in the try block is not handled in the catch block, then the default handling mechanism handles it and the rest of the program executes as it is. This is shown by the following code:

public class ClassInterFace{
    public static void main(String arg[]){
        int[] arr= {1,2,3,3};

        try{
            int c= arr[5];//array index out of bound exception will be raised

              System.out.println("Statement of try block");
         
        }
        catch(ArithmeticException c){
            //only arithmetic exceptions can be handled, thus it is not an appropriate handler
            System.out.println("Exception caught");

        }
        finally{
            System.out.println("Final block executed");

        }
    }
}

Output:

Final block executedException in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 4
at ClassInterFace.main(ClassInterFace.java:7)

write your code here: Coding Playground

Case 3

Exception is not raised in the try block.

Here, the catch block will never be executed as it can be executed only if an exception occurs. The try catch finally in java without any exception is demonstrated below:

public class ClassInterFace{
    public static void main(String arg[]){
     
        try{
            String s= "123";
            int a= Integer.parseInt(s);


              System.out.println("Statement of try block");
         
        }
        catch(Exception c){
            //catch block will not run without exception is raised
            System.out.println("Exception caught");

        }
        finally{
            System.out.println("Final block executed");

        }
    }
}

Output:

Statement of try block
Final block executed

write your code here: Coding Playground

Control Flow using Try-Finally Block

Here, the only possibility is that the exception is raised in Try Block and it may not be raised. If there is no exception in Try Block, then finally block will be executed after the try block exits. Then, the rest of the program will be executed. This is demonstrated in the code given below:

public class ClassInterFace{
    public static void main(String arg[]){
     
        try{
           
          int[] a= {2,3,4,5};
          System.out.println(a[3]);

              System.out.println("Statement of try block");
         
        }
       
        finally{
            System.out.println("Final block executed");

        }
            System.out.println("Outside try-catch-finally");
    }
}

Output:

5
Statement of try block
Final block executed
Outside try-catch-finally

write your code here: Coding Playground

On other hand, if an exception occurs in the try block, then the finally block executes after which the default handling mechanism executes. Its implementation is given below:

public class ClassInterFace{
    public static void main(String arg[]){
     
        try{
           
          int[] a= {2,3,4,5};
          System.out.println(a[6]);

              System.out.println("Statement of try block");
         
        }
       
        finally{
            System.out.println("Final block executed");

        }
            System.out.println("Outside try-catch-finally");
    }
}

Output:

Final block executed
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 6 out of bounds for length 4
at ClassInterFace.main(ClassInterFace.java:7)

write your code here: Coding Playground

This is how you can handle the exception and maintain the control flow using the concept of try catch finally in Java.