×

Java Exception Propagation

Java Exception Propagation

When an exception is being thrown from the peak of the stack and not getting caught, it runs down the stack to the previous method, which is sitting immediately behind the peek method. If the exception is not caught, then again, it goes down to the next previous method, and the propagation continues till the exception is caught.The list of the methods that are present in the stack is called as call stack, whereas the process by which an exception propagates from peak to bottom of a stack is known as the Java Exception Propagation.

Propagation in Unchecked Exception

By default, Java facilitates the propagation of an unchecked exception in the call stack. Let’s confirm the same with the help of the following program.

FileName: ExceptionPropagationExample.java

 public class ExceptionPropagationExample
{
void m1()
{
    // Arithmetic Exception occurred which is an unchecked exception
    int i = 51 / 0;
    // propagating the exception to m2()
}
void m2()
{
    m1();
    // propagating the exception to m3()
}
void m3()
{
    try
    {
        m2();
    }
    // handling any raised exception in the catch block
    catch (Exception e)
    {
System.out.println("Handling exception in the catch block " + e);
    }
}
// main method
public static void main(String argvs[])
{
    // Creating an object of the ExceptionPropagationExample class
ExceptionPropagationExample  obj = new ExceptionPropagationExample ();
    // invoking the method m3()
    obj.m3();
System.out.println("The normal flow ...");
}
} 

Output:

Java Exception Propagation

Explanation:The method m3() invokes the method m2(), which in turn invokes the method m1(). In the method m1(), an unchecked exception is raised. The Java runtime system tries to tackle the exception. However, the system finds no code to handle the exception in m1(). Therefore, it goes down the stack and looks for the exception handling code in m2(). However, this time also, the search goes in vain, and the search continues in the bottom last method present in the stack, and this time the code handling the exception is found, which handles the raised exception of the method m1(). The call stack is described in the following diagram.

Java Exception Propagation

Propagation inchecked Exception

In the checked exception, the propagation of exception does not occur by default. Observe the following program.

FileName: ExceptionPropagationExample1.java

 // import statement
import java.io.IOException;
public class ExceptionPropagationExample1
{
// a method that throws a checked exception
void m1()
{
    // throwing the IOException, which is a checked exception
    throw new IOException("device error");
    // propagating the exception to m2()
}
void m2()
{
    m1();
    // propagating the exception to m3()
}
void m3()
{
    try
    {
        m2();
    }
    // handling any raised exception in the catch block
    catch (Exception e)
    {
System.out.println("Handling exception in the catch block " + e);
    }
}
// main method
public static void main(String argvs[])
{
    // Creating an object of the ExceptionPropagationExample1 class
    ExceptionPropagationExample1  obj = new ExceptionPropagationExample1 ();
    // invoking the method m3()
    obj.m3();
System.out.println("The normal flow ...");
}
} 

Output:

Java Exception Propagation

Explanation:The output confirms that the program has not terminated normally. It is because the checked exception raised in the method m1() has not been handled. We also see that m3() is willing to handle the exception using the try-catch block. However, the IOException raised in the m1() method never gets propagated to the method m3(). Thus, we see that the checked exception does not propagate on its own.

Forcing the Propagation in the Checked Exception

There can be a scenario when one needs to propagate the checked exception. To achieve the same, one needs to use the throws keyword. The following program illustrates the same.

FileName: ExceptionPropagationExample2.java

 // import statement
import java.io.IOException;
public class ExceptionPropagationExample2
{
// a method that throws a checked exception
// and propagates the exception handling
// responsibility to the caller method
void m1() throws IOException
{
    // throwing the IOException, which is a checked exception
    throw new IOException("device error");
    // propagating the exception to m2()
}
// the method m2() also propagates the exception handling
// responsibility to the caller method
void m2() throws IOException
{
    m1();
    // propagating the exception to m3()
}
void m3()
{
    try
    {
        m2();
    }
    // handling any raised exception in the catch block
    catch (Exception e)
    {
System.out.println("Handling exception in the catch block " + e);
    }
}
// main method
public static void main(String argvs[])
{
    // Creating an object of the ExceptionPropagationExample2 class
    ExceptionPropagationExample2  obj = new ExceptionPropagationExample2 ();
    // invoking the method m3()
    obj.m3();
System.out.println("The program ended with the normal flow ...");
}
} 

Output:

Java Exception Propagation

Explanation:We observer that the program terminated normally. It happened because of the throws keyword. The throws keyword provides the path to the raised exception from the method m1() to m3() via method m2().


Related Topics

How to Convert String to float in Java

How to Convert String to Float in java It is used if you want to perform mathematical operations on the string that contains float number. You can convert String to float...

3 minutes read.

Monsoon Umbrella Problem in Java

The Monsoon Umbrella problem is a classic Java programming problem used to test the skills of a programmer. The problem involves writing a program to determine the number of umbrellas...

3 minutes read.

Banking Application in Java

JDBC (Java Database Connectivity), which provides an API to connect to, execute, and fetch data from any databases, can be used to handle transactions in Java. There are several factors...

7 minutes read.

How to Convert long to int in Java

How to Convert long to int in Java When we assign a larger type value to a variable of smaller type, then we need to perform explicit casting for the conversion....

2 minutes read.

URLConnection class in Java

A communication channel between the URL and the program is represented by the Java URLConnection class. It may be utilized to read from and write to the given resource the...

4 minutes read.

Bad Operand types for Binary Operator Java

We will discuss how to handle issues in bad operand types for binary operator &, bad operand types for binary operator &&, bad operand types for binary operator ==, and...

4 minutes read.

How to check version of java in Linux

Java is one of the most famous and thoroughly utilized programming tongues from one side of the world to the other. On the off chance that you are a Java...

2 minutes read.

Types of Assignment Operators in Java

In this tutorial, we are going to study assignment operators and their types in Java language. Before proceeding to the types, let us know the term ‘assignment operator’.  The assignment...

5 minutes read.

Generics vs Wildcard in Java

In generic programming, the question mark (?) is often referred to as the wildcard. It stands for a mysterious type. The wildcard can be used for many different contexts, such as...

4 minutes read.

House Numbers in Java

In this section, we will discuss about house number in Java. It is a sum of cubes, each of which has a dimension of h + 1. There is a...

3 minutes read.

Java Garbage Collection Interview Questions

One of the key areas of Java is garbage collection. Garbage collection enables apps to manage memory automatically. Interviewers frequently ask inquiries about garbage collection. Q1: What is the purpose of...

6 minutes read.

Java Math floor() Method

The floor() method of Math class returns the largest double value that is equal to a mathematical integer and is less than or equal to the argument. Syntax: public static double floor(double...

2 minutes read.

How to override toString() method in Java?

Java is an object-oriented language. It only works with classes and objects. Thus, whenever we need to calculate, we need an object or objects that belong to the class. The Java method...

2 minutes read.

Types of Sockets in Java

The fundamental idea behind Java's networking capability is the socket. Early in the 1980s, the Berkeley UNIX 4.2BSD version included the socket paradigm. Berkeley socket is the term employed as...

9 minutes read.

Functional Interfaces in Java

Java has forever remained an Object-Oriented Programming language. By object-oriented programming language, we can declare that everything present in the Java programming language rotates throughout the Objects, except for some...

11 minutes read.

Java 8 Multimap

Java comes with several practical built-in collection libraries. However, there are situations when we need specialized collections that are not included in the Java standard library. The Multimap is one...

7 minutes read.

Star Pattern Programs in Java

Star Pattern Programs in Java The star pattern programs in Java is the part of pattern programs in Java, which we discussed earlier. Right Triangle Star Pattern Filename: StarPatternExample.java public class StarPatternExample {              public static void...

4 minutes read.

GCD Program in Java

GCD Program in Java The GCD program in Java outputs the GCD of the given numbers. In mathematics, Greatest Common Divisor (GCD), Greatest Common Factor or Highest Common Factor (HCF) of...

14 minutes read.

Timestamp Operation in Java

JDBC escape syntax is supported by Timestamp's formatting and parsing functions. Additionally, it adds support for fractional seconds values for SQL TIMESTAMP.java.util.Date is wrapped in a lightweight wrapper that enables...

3 minutes read.

How to create a linked list in Java

Introduction: The linked listing is one type of linear statistics shaped like an array. Not like arrays, linked listing factors aren't stored in a contiguous place. The elements have linked...

3 minutes read.