The Wayback Machine - https://web.archive.org/web/20240616181648/https://www.geeksforgeeks.org/flow-control-in-try-catch-finally-in-java/
Open In App

Flow control in try catch finally in Java

Last Updated : 28 Feb, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we’ll explore all the possible combinations of try-catch-finally which may happen whenever an exception is raised and how the control flow occurs in each of the given cases. 

  1. Control flow in try-catch clause OR try-catch-finally clause 
    • Case 1: Exception occurs in try block and handled in catch block
    • Case 2: Exception occurs in try-block is not handled in catch block
    • Case 3: Exception doesn’t occur in try-block
  2. try-finally clause 
    • Case 1: Exception occurs in try block
    • Case 2: Exception doesn’t occur in try-block

Control flow in try-catch OR try-catch-finally 

1. Exception occurs in try block and handled in catch block: If a statement in try block raised an exception, then the rest of the try block doesn’t execute and control passes to the corresponding catch block. After executing the catch block, the control will be transferred to finally block(if present) and then the rest program will be executed. 

  • Control flow in try-catch:

Java




// Java program to demonstrate
// control flow of try-catch clause
// when exception occur in try block
// and handled in catch block
class GFG
{
    public static void main (String[] args)
    {
         
        // array of size 4.
        int[] arr = new int[4];
        try
        {
            int i = arr[4];
                 
            // this statement will never execute
            // as exception is raised by above statement
            System.out.println("Inside try block");
        }
        catch(ArrayIndexOutOfBoundsException ex)
        {
            System.out.println("Exception caught in Catch block");
        }
         
        // rest program will be executed
        System.out.println("Outside try-catch clause");
    }
}


Output

Exception caught in Catch block
Outside try-catch clause
  • Control flow in try-catch-finally clause :

Java




// Java program to demonstrate
// control flow of try-catch-finally clause
// when exception occur in try block
// and handled in catch block
class GFG
{
    public static void main (String[] args)
    {
         
        // array of size 4.
        int[] arr = new int[4];
         
        try
        {
            int i = arr[4];
                 
            // this statement will never execute
            // as exception is raised by above statement
            System.out.println("Inside try block");
        }
         
        catch(ArrayIndexOutOfBoundsException ex)
        {
            System.out.println("Exception caught in catch block");
        }
         
        finally
        {
            System.out.println("finally block executed");
        }
         
        // rest program will be executed
        System.out.println("Outside try-catch-finally clause");
    }
}


Output

Exception caught in catch block
finally block executed
Outside try-catch-finally clause

2. Exception occurred in try-block is not handled in catch block: In this case, the default handling mechanism is followed. If finally block is present, it will be executed followed by the default handling mechanism. 

  • try-catch clause :

Java




// Java program to demonstrate
// control flow of try-catch clause
// when exception occurs in try block
// but not handled in catch block
class GFG
{
    public static void main (String[] args)
    {
         
        // array of size 4.
        int[] arr = new int[4];
        try
        {
            int i = arr[4];
                 
            // this statement will never execute
            // as exception is raised by above statement
            System.out.println("Inside try block");
        }
         
        // not a appropriate handler
        catch(NullPointerException ex)
        {
            System.out.println("Exception has been caught");
        }
         
        // rest program will not execute
        System.out.println("Outside try-catch clause");
    }
}


Run Time Error: 

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
    at GFG.main(GFG.java:12)
  • try-catch-finally clause :

Java




// Java program to demonstrate
// control flow of try-catch-finally clause
// when exception occur in try block
// but not handled in catch block
class GFG
{
    public static void main (String[] args)
    {
         
        // array of size 4.
        int[] arr = new int[4];
         
        try
        {
            int i = arr[4];
                 
            // this statement will never execute
            // as exception is raised by above statement
            System.out.println("Inside try block");
        }
         
        // not a appropriate handler
        catch(NullPointerException ex)
        {
            System.out.println("Exception has been caught");
        }
         
        finally
        {
            System.out.println("finally block executed");
        }
         
        // rest program will not execute
        System.out.println("Outside try-catch-finally clause");
    }
}


Output : 

finally block executed

Run Time error: 

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
    at GFG.main(GFG.java:12)

3. Exception doesn’t occur in try-block: In this case catch block never runs as they are only meant to be run when an exception occurs. finally block(if present) will be executed followed by rest of the program. 

  • try-catch clause :

Java




// Java program to demonstrate try-catch
// when an exception doesn't occurred in try block
class GFG
{
    public static void main (String[] args)
    {
         
        try
        {
             
            String str = "123";
                 
            int num = Integer.parseInt(str);
                 
            // this statement will execute
            // as no any exception is raised by above statement
            System.out.println("Inside try block");
             
        }
         
        catch(NumberFormatException ex)
        {
                 
            System.out.println("catch block executed...");
                 
        }
 
        System.out.println("Outside try-catch clause");
    }
}


Output

Inside try block
Outside try-catch clause
  • try-catch-finally clause 

Java




// Java program to demonstrate try-catch-finally
// when exception doesn't occurred in try block
class GFG
{
    public static void main (String[] args)
    {
         
    try
    {
         
        String str = "123";
             
        int num = Integer.parseInt(str);
             
        // this statement will execute
        // as no any exception is raised by above statement
        System.out.println("try block fully executed");
         
    }
     
    catch(NumberFormatException ex)
    {
             
        System.out.println("catch block executed...");
             
    }
     
    finally
    {
        System.out.println("finally block executed");
    }
 
    System.out.println("Outside try-catch-finally clause");
    }
}


Output

try block fully executed
finally block executed
Outside try-catch-finally clause

Control flow in try-finally

In this case, no matter whether an exception occurs in try-block or not finally will always be executed. But control flow will depend on whether an exception has occurred in the try block or not. 

1. Exception raised: If an exception has occurred in the try block then the control flow will be finally block followed by the default exception handling mechanism.

Java




// Java program to demonstrate
// control flow of try-finally clause
// when exception occur in try block
class GFG
{
    public static void main (String[] args)
    {
         
        // array of size 4.
        int[] arr = new int[4];
        try
        {
            int i = arr[4];
                 
            // this statement will never execute
            // as exception is raised by above statement
            System.out.println("Inside try block");
        }
         
        finally
        {
            System.out.println("finally block executed");
        }
         
        // rest program will not execute
        System.out.println("Outside try-finally clause");
    }
}


Output : 

finally block executed
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
    at GFG.main(GFG.java:11)

2. Exception not raised: If an exception does not occur in the try block then the control flow will be finally block followed by the rest of the program

Java




// Java program to demonstrate
// control flow of try-finally clause
// when exception doesn't occur in try block
class GFG
{
    public static void main (String[] args)
    {
         
        try
        {
            String str = "123";
             
            int num = Integer.parseInt(str);
             
            // this statement will execute
            // as no any exception is raised by above statement
            System.out.println("Inside try block");
        }
         
        finally
        {
            System.out.println("finally block executed");
        }
         
        // rest program will be executed
        System.out.println("Outside try-finally clause");
    }
}


Output

Inside try block
finally block executed
Outside try-finally clause

Related Articles:  

 



Previous Article
Next Article

Similar Reads

Java Try Catch Block
In Java exception is an "unwanted or unexpected event", that occurs during the execution of the program. When an exception occurs, the execution of the program gets terminated. To avoid these termination conditions we can use try catch block in Java. In this article, we will learn about Try, catch, throw, and throws in Java. Why Does an Exception o
4 min read
Output of Java Programs | Set 41 (try-catch)
Prerequisite : try-catch, Exception Handling1. What will be the output of the following program? Java Code class Geeks { public static void main(String[] args) { try { System.out.println(1/0); } catch(ArithmeticException e) { System.out.println(e.getMessage()); } } } Options: 1. java.lang.ArithmeticExcetion 2. / by zero 3. java.lang.ArithmeticExcet
3 min read
Java Program to Use finally block for Catching Exceptions
The finally block in java is used to put important codes such as clean up code e.g. closing the file or closing the connection. The finally block executes whether exception rise or not and whether exception handled or not. A finally contains all the crucial statements regardless of the exception occurs or not. There are 3 possible cases where final
3 min read
Why You Need to Close the Java Streams in Finally Block?
In Java finally block is a block used to execute important and common code. The finally block is mostly used during exception handling with try and catch to close streams and files. The code in finally block is executed irrespective of whether there is an exception or not. This ensures that all the opened files are properly closed and all the runni
2 min read
final, finally and finalize in Java
This is an important question concerning the interview point of view. final keyword final (lowercase) is a reserved keyword in java. We can't use it as an identifier, as it is reserved. We can use this keyword with variables, methods, and also with classes. The final keyword in java has a different meaning depending upon whether it is applied to a
13 min read
Static Control Flow in Java
Static Control Flow decides the sequence of activities/steps that will be executed in order when we run a java class that contains static variables, methods, and blocks. This article will explain how static control flow occurs whenever a Java program is executed. Prerequisite: Static Blocks The Static Control Flow mechanism performs the following 3
4 min read
Instance Control Flow in Java
This article will explain how Instance Control Flow takes place whenever objects are created. Instance Control Flow In Normal Class Whenever we are executing a java .class file, 1st Static Control Flow will be executed. In the Static Control Flow, if we are creating an object the following sequence of steps will be executed as part of Instance Cont
7 min read
Static Control Flow with Inherited Classes in Java
Before understanding the static control flow of a program, we must be familiar with the following two terms: Class loading: It refers to reading the .class file and loading it into the memory(JVM). Java loads classes dynamically, that is, classes are loaded on demand only when they are referred.Class initialization: It refers to executing and initi
6 min read
Using throw, catch and instanceof to handle Exceptions in Java
Prerequisite : Try-Catch Block in Java In Java, it is possible that your program may encounter exceptions, for which the language provides try-catch statements to handle them. However, there is a possibility that the piece of code enclosed inside the 'try' block may be vulnerable to more than one exceptions. For example, take a look at the followin
4 min read
Java Program to use Catch to Handle the Exception
The exception is the event occurs when the program is executing. Due to this exception, the normal flow of the program will get disrupts. Whenever an exception occurs in the method, the method creates an object and sends that object to the runtime system. For example, the file needs to be open is not found, class not found exception, Arithmetic Exc
3 min read