BeginnersBook

  • Home
  • Java
    • Java OOPs
    • Java Collections
    • Java Examples
  • C
    • C Examples
  • C++
    • C++ Examples
  • DBMS
  • Computer Network
  • Python
    • Python Examples
  • More…
    • jQuery
    • Kotlin
    • WordPress
    • SEO
    • JSON
    • JSP
    • JSTL
    • Servlet
    • MongoDB
    • XML
    • Perl

Flow control in try-catch-finally in Java

Last Updated: September 13, 2022 by Chaitanya Singh | Filed Under: java

In this guide, you will learn how to use try-catch along with finally block in Java. We will cover various examples to see, how try catch and finally works together during exception handling.

Scenario 1: Exception doesn’t occur in try block

If exception doesn’t occur in try block then all the catch blocks are ignored, however the finally block executes (if it is present) because it executes whether exception occurs or not.

Case 1: try-catch block with no finally block:

class JavaExample
{
  public static void main(String args[])
  {
    int x = 10;
    int y = 10;
    try{
      int num= x/y;
      System.out.println("Remaining statements inside try block");
    }
    catch(Exception ex)
    {
      System.out.println("Exception caught in catch block");
    }
    System.out.println("Statements Outside of try-catch");
  }
}

Output:

Remaining statements inside try block
Statements Outside of try-catch

Case 2: Same scenario with try-catch-finally clause:

public class JavaExample {
  public static void main(String args[]){
    //declared and initialized two variables
    int num1 =10, num2 = 5;
    try
    {
      int div = num1/num2;

      // if exception occurs in the above statement then this
      // statement will not execute else it will execute
      System.out.println("num1/num2: "+div);
    }
    catch(ArithmeticException e)
    {
      System.out.println("Catch block: ArithmeticException caught");
    }
    finally{
      System.out.println("Finally block: I will always execute");
    }

    // rest of the code
    System.out.println("Outside try-catch-finally");
  }
}

Output:
Try Catch Finally in Java

Scenario 2: Exception occurred in try block and handled in catch block

If exception occurs in try block then the rest of the statements inside try block are ignored and the corresponding catch block executes. After catch block, the finally block executes and then the rest of the program.

In the following example, an Arithmetic exception occurred as the number is divided by zero, there is a catch block to handle Arithmetic exception so the control got transferred to it. After which the statements inside finally block (if present) are executed.

Case 1: try-catch without finally:

class JavaExample
{
  public static void main(String args[])
  {
    int x = 10;
    int y = 0;
    try{
      int num= x/y;
      System.out.println("Remaining statements inside try block");
    }
    catch(Exception ex)
    {
      System.out.println("Exception caught in catch block");
    }
    System.out.println("Statements Outside of try-catch");
  }
}

Output:

Exception caught in catch block
Statements Outside of try-catch

Point to note in above example: There are two statements present inside try block. Since exception occurred because of first statement, the second statement didn’t execute. Hence we can say that if an exception occurs then the rest of the statements in try block don’t execute and control passes to catch block.

Case 2: try-catch with finally:

public class JavaExample {
  public static void main(String args[]){
    //now the second variable is initialized with 0 value
    int num1 =10, num2 = 0;
    try
    {
      int div = num1/num2;

      // if exception occurs in the above statement then this
      // statement will not execute else it will execute
      System.out.println("num1/num2: "+div);
    }
    catch(ArithmeticException e)
    {
      System.out.println("Catch block: ArithmeticException caught");
    }
    finally{
      System.out.println("Finally block: I will always execute");
    }

    // rest of the code
    System.out.println("Outside try-catch-finally");
  }
}

Output:
Try Catch Finally in Java

Scenario 3: Exception occurred in try block and not handled in catch block

If the exception raised in try block is not handled in catch block then the rest of the statements in try block and the statements after try-catch-finally doesn’t execute, only the finally block executes and a system generated error message for the exception that occurred in try block.

In the following example, the ArithmeticException occurred in try block but there is no catch block that can handle ArithmeticException so after the execution of finally block, a system generated error message is displayed.

public class JavaExample {
  public static void main(String args[]){
    //now the second variable is initialized with 0 value
    int num1 =10, num2 = 0;
    try
    {
      int div = num1/num2;

      // if exception occurs in the above statement then this
      // statement will not execute else it will execute
      System.out.println("num1/num2: "+div);
    }
    //this cannot handle ArithmeticException
    catch(ArrayIndexOutOfBoundsException e)
    {
      System.out.println("Catch block: ArrayIndexOutOfBoundsException caught");
    }
    finally{
      System.out.println("Finally block executed");
    }

    // rest of the code
    System.out.println("Outside try-catch-finally");
  }
}

Output:
Try Catch Finally when exception not handled

Flow of control in try catch finally in Java:

To summarise everything we have learned so far:

  1. If exception occurs in try block then control immediately transfers(skipping rest of the statements in try block) to the catch block. Once catch block finished execution then finally block and after that rest of the program.
  2. If no exception occurs in try block, then try block gets executed completely and then control gets transferred to finally block (skipping catch blocks), after which rest of the statements after try-catch-finally are executed.

Recommended Posts:

  • Try catch in Java
  • Finally in Java
  • Throw vs throws in Java
  • Multiple catch blocks in Java
❮ PreviousNext ❯

Top Related Articles:

  1. Nested try catch block in Java – Exception handling
  2. Exception handling in Java with examples
  3. Java Variables: Declaration, Scope, and Naming Conventions
  4. What is case Keyword in Java
  5. Interface in java with example programs

Tags: Exception-Handling

About the Author

I have 15 years of experience in the IT industry, working with renowned multinational corporations. Additionally, I have dedicated over a decade to teaching, allowing me to refine my skills in delivering information in a simple and easily understandable manner.

– Chaitanya

Comments

  1. karthik says

    November 2, 2014 at 5:43 PM

    it is very useful to me… gud concept ….explanation of program is also gud…

    Reply
  2. Michael says

    January 5, 2015 at 5:23 PM

    I am having a little trouble with Exception handling as I am new to Java.

    I need to make a comparison application that handles incorrect input type (integers are needed, nothing else) that stores the last-known correct input and continues from there.

    Is there a way you can help me with this?

    Reply
  3. Caroline says

    March 30, 2016 at 6:46 PM

    Why doesn’t the last example print out “end – myMethod” at the end? Is it because in the method, it caught an exception as testnum = 12?

    Reply
  4. sai divya sree says

    June 26, 2016 at 10:37 PM

    wow…this article made my understanding of flow control in try/catch/finally more easy..Thanks a lot.

    Reply

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Java Tutorial

Java Introduction

  • Java Index
  • Java Introduction
  • History of Java
  • Features of Java
  • C++ vs Java
  • JDK vs JRE vs JVM
  • JVM - Java Virtual Machine
  • First Java Program
  • Variables
  • Data Types
  • Operators

Java Flow Control

  • Java If-else
  • Java Switch-Case
  • Java For loop
  • Java while loop
  • Java do-while loop
  • Continue statement
  • break statement

Java Arrays

  • Java Arrays

OOPs Concepts

  • OOPs Concepts
  • Constructor
  • Java String
  • Static keyword
  • Inheritance
  • Types of inheritance
  • Aggregation
  • Association
  • Super Keyword
  • Method overloading
  • Method overriding
  • Overloading vs Overriding
  • Polymorphism
  • Types of polymorphism
  • Static and dynamic binding
  • Abstract class and methods
  • Interface
  • Abstract class vs interface
  • Encapsulation
  • Packages
  • Access modifiers
  • Garbage Collection
  • Inner classes
  • Static import
  • Static constructor

Java Exception Handling

  • Exception handling
  • Java try-catch
  • Java throw
  • Java throws
  • Checked and Unchecked Exceptions
  • Jav try catch finally
  • Exception Examples
  • Exception Propagation

Collections Framework

  • Collections in Java
  • Java ArrayList
  • Java LinkedList
  • Java Vector
  • Java HashSet
  • Java LinkedHashSet
  • Java TreeSet
  • Java HashMap
  • Java TreeMap
  • Java LinkedHashMap
  • Java Queue
  • Java PriorityQueue
  • Java Deque
  • Comparable interface
  • Comparator interface
  • Collections Interview Questions

MORE ...

  • Java Scanner Class
  • Java 8 Features
  • Java 9 Features
  • Java Conversion
  • Java Date
  • Java Multithreading
  • Java I/O
  • Java Serialization
  • Java Regex
  • Java AWT
  • Java Swing
  • Java Enum
  • Java Annotations
  • Java main method
  • Java Interview Q

Copyright © 2012 – 2025 BeginnersBook . Privacy Policy . Sitemap