Table of contents
1.
Introduction
2.
Syntax
3.
Multiple Catch Blocks
4.
The Flow of Control
4.1.
An exception occurs:
4.2.
An exception does not occur:
5.
Try Catch and Finally Blocks
5.1.
An exception occurs
5.2.
An exception does not occur
5.3.
A special case
6.
Frequently Asked Questions
7.
Conclusion
Last Updated: Mar 27, 2024

Flow control in Try-Catch and Finally Blocks in Java

Author Vasu Bansal
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

In this article, we will discuss flow control in try-catch and finally blocks in Java. These blocks are used for exception handling in Java. They help the programmer catch any exception that may arise while the program is running.

Coding Ninjas also have a four-blog series on Java exceptions and exception handling. Here's a step-by-step guide to help you get the most out of this series.

This may sound daunting at first, but once you've completed the series, exceptions in Java will be a breeze for you.

Syntax

The following is the syntax of the try, catch and finally blocks in Java. It is a common practice to place the code in which there may arise exceptions in the try block. This way, we can actually catch and handle exceptions without our programming crashing. 

try{
// Write code here
}
catch (Exception e){
// Write code here
}
finally{
// Write code here
}

Multiple Catch Blocks

There is a possibility of more than one type of exception that may arise in a program. So for catching particular types of exceptions, we can use the following syntax.

try{
// Write code here
}
catch (ExceptionType_1 e1){
// Write code here
}
catch (ExceptionType_2 e2){
// Write code here
}
catch (ExceptionType_3 e3){
// Write code here
}
catch (ExceptionType_4 e4){
// Write code here
}
finally{
// Write code here
}


Also see,  Swap Function in Java

The Flow of Control

The following two cases may arise in front of you when you write a Java program.

An exception occurs:

The main reason for using try-catch blocks is to handle cases when the program raises an exception. So let us consider the following example in which the program raises an exception.

Code:

public class Main {
    public static void main(String[] args){
        int num1 = 100;
        int num2 = 0;
        System.out.println("Program Starts");
        try {
            System.out.println("Inside Try Block");
            int res = num1/num2;
            System.out.println("The line after exception in the try block, the value of res: " + res);          
        }
        catch (Exception exp) {
            System.out.println("Inside Catch Block");
        }
        System.out.println("End of the program");
    }
}

Output:

Program Starts
Inside Try Block
Inside Catch Block
End of the program

So as you can see in the above program, dividing by zero leads to an exception. Therefore, as soon as the program reaches the line where the exception is raised, the flow control jumps directly to the program written in the catch blocks. All the lines written in the try block below the line that raised the exception are thereby not executed. 

Try it on online java compiler.

An exception does not occur:

The second case is a fairly simple case in which the code raises no exception. Consider the program given in the previous section. As a minor change this time, replace the value of num2 from 0 to 10.

Code:

public class Main {
    public static void main(String[] args){
        int num1 = 100;
        int num2 = 10;
        System.out.println("Program Starts");
        try {
            System.out.println("Inside Try Block");
            int res = num1/num2;
            System.out.println("The line after exception in the try block, the value of res: " + res);          
        }
        catch (Exception exp) {
            System.out.println("Inside Catch Block");
        }
        System.out.println("End of the program");
    }
}

Output:

Program Starts
Inside Try Block
The line after exception in the try block, the value of res: 10
End of the program

Try Catch and Finally Blocks

In this section, we will consider the case when we have all of the three blocks, i.e. try, catch, and finally blocks.

An exception occurs

We take the same example as discussed in the previous section. The only change that we make here is that we have added the finally block after the try-catch blocks. The code in the try block will raise an exception due to division by zero. 

Code:

public class Main {
    public static void main(String[] args){
        int num1 = 100;
        int num2 = 0;
        System.out.println("Start of program");
        try {
            System.out.println("Inside Try Block");
            int res = num1/num2;
            System.out.println("The line after exception in the try block, the value of res: " + res);          
            System.out.println("End of Try Block");
        }
        catch (Exception exp) {
            System.out.println("Inside Catch Block");
            System.out.println("End of Catch Block");
        }
        finally{
            System.out.println("Inside Finally Block");
            System.out.println("End of Finally Block");
        }
        System.out.println("End of the program");
    }
}

Output:

Start of program
Inside Try Block
Inside Catch Block
End of Catch Block
Inside Finally Block
End of Finally Block
End of the program

 

So as you can see in the above program, dividing by zero leads to an exception. Therefore, as soon as the program reaches the line where the exception is raised, the flow control jumps directly to the program written in the catch blocks. All the lines written in the try block below the line that raised the exception are thereby not executed. Additionally, after the code written in the catch block is executed, the code flow jumps to the finally block and all the code written in that block is executed.

An exception does not occur

This time we have a program such that the code written inside the try block raises no exception. In this case, as you might have guessed correctly by now, the code flow first enters the try block executing all the code written in it. Since there was no exception in the code this time, the flow jumps to the finally block, skipping the catch block.

Code:

public class Main {
    public static void main(String[] args){
        int num1 = 100;
        int num2 = 10;
        System.out.println("Start of program");
        try {
            System.out.println("Inside Try Block");
            int res = num1/num2;
            System.out.println("The line after exception in the try block, the value of res: " + res);          
            System.out.println("End of Try Block");
        }
        catch (Exception exp) {
            System.out.println("Inside Catch Block");
            System.out.println("End of Catch Block");
        }
        finally{
            System.out.println("Inside Finally Block");
            System.out.println("End of Finally Block");
        }
        System.out.println("End of the program");
    }
}

Output:

Start of program
Inside Try Block
The line after exception in the try block, the value of res: 10
End of Try Block
Inside Finally Block
End of Finally Block
End of the program

A special case

We see a special behaviour in the program having try, catch and finally blocks when the try block contains a return statement. When the program flow encounters a return statement in the try block, it does not directly return from the try block where it encountered the return statement. Instead, it first goes to the finally block and executes the code written in it. After executing the finally block, it again returns to the return statement in the try block and returns from the program. You will get more clarity on this by seeing the example below.

Code:

public class Main {
    public static void main(String[] args){
        System.out.println("Start of program");
        try {
            System.out.println("Inside Try Block");
            return;
        }
        catch (Exception exp) {
            System.out.println("Inside Catch Block");
            System.out.println("End of Catch Block");
        }
        finally{
            System.out.println("Inside Finally Block");
            System.out.println("End of Finally Block");
        }
        System.out.println("End of the program");
    }
}

Output:

Start of program
Inside Try Block
Inside Finally Block
End of Finally Block

 

Must Read Static Blocks In Java, Duck Number in Java and Hashcode Method in Java

Frequently Asked Questions

  1. Can a program have a catch clause without a try block?
    No, it is not possible to have a catch clause without a try block. Every catch clause must be associated with one or another try block.
     
  2. Is it compulsory to always have a finally block?
    No, there is no compulsion to have a finally block for each of the try and catch blocks in the code.
     
  3. Can I write code between the try, catch and finally blocks?
    No, you cannot write any code between the try, catch and finally blocks. 

Conclusion

In this article, we have extensively discussed Flow control in try-catch and finally blocks in Java. You can also read the blog Server Socket Class in Java on the Coding Ninjas Website to enhance your skills.

We hope this blog has helped you enhance your knowledge regarding Flow Control in Java. If you want to learn more, check out our Android Development Course on the Coding Ninjas Website to learn everything you need to know about Android development. Do upvote our blog to help other ninjas grow. Happy Coding!

Live masterclass