×

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

Number Pattern Programs in Java

Number Pattern Programs in Java: Number pattern programs are part of pattern programs. In the previous section, we have learned the approach to print the pattern program in Java. To...

6 minutes read.

Why to use Enum in Java?

In this article, you will be acknowledged about the Enum in java, its uses and mainly its purpose. Enum has various functionalities. Each of them will be discussed. Enum In a computer...

3 minutes read.

Best Java IDE

Applications for desktop, workplace, smartphone, and the internet can be created using Java, one of the most popular programming languages. Java will undoubtedly be a popular programming language for so...

5 minutes read.

Java Code Coverage Tools

Code coverage testing is a crucial metric that gauges how thoroughly the program's source code has been tested. The market is flooded with Code Coverage Tools, making it difficult to...

7 minutes read.

Menu Driven Program in Java

Menu Driven Program in Java The menu-driven program in Java is a program that displays a menu and then takes input from the user to choose an option from the displayed...

3 minutes read.

Difference Between in Java and C++

FeatureC++JavaDefinitionC++ is a general programming language created by Bjarne Stroustrup as an extension of c language    Java is class-based, object-based, and designed to have as few implementation dependencies as...

4 minutes read.

Java Math tanh() Method

The tanh() method of Java Math class returns the hyperbolic tangent of the specified double value. Syntax: public static double tanh(double x) Parameters: The parameter ‘x’ represents the number whose hyperbolic tangent is to...

2 minutes read.

How to create an array in Java

An array is a linear data structure stores a collection of fixed number ofelements of similar type. The size of an array is specified when it is created. The array...

14 minutes read.

Java Byte Keyword

Byte: The Keyword Byte in Java programming language is a primitive data type.Digital content that is most used for eight bits is called as a byte.The Java Byte Keyword is used...

3 minutes read.

Split the Number String into Primes in Java

Given is a string that only contains digits and serves to represent a number. Our goal is to split the string of numbers in a way that ensures each segment...

2 minutes read.

Skyline Problem in Java

The skyline of a city is the outer edge of the pattern created by all of its structures when viewed from a distance. Return the skyline that these buildings together...

4 minutes read.

Java Switch string

A multi-way branch statement is the switch statement. It offers a simple method for allocating execution to various code sections according to the expression's value. Primitive data types, including bytes,...

3 minutes read.

How to take Array Input in Java

In this tutorial, we will learn about how to take array input in Java. So, before taking inputs let us know what an array is first. Array: An array is a collection...

10 minutes read.

Mutable class in Java

A language for object-oriented programming is Java. Because this is an object-oriented language of programming, all of its mechanisms and methods are based on objects. Java has a concept of...

6 minutes read.

How to Convert Object to String in Java

How to Convert Object to String in Java You can convert any Object to String in Java whether it is a user-defined class, StringBuilder or StringBuffer, etc. There are two methods...

2 minutes read.

Java Extends vs Implements

Java: We known that the java is a pure object oriented programming language. Java programming language consists of many features such as portable, plat form independence, secured, robust, simple, architecture neutral,...

4 minutes read.

Java Math log1p() Method

The log1p() method of Math class returns the natural logarithmic sum for the specified double argument and 1. Its value is much closer to result of ln(1 + x). Syntax: public static...

2 minutes read.

The Maximum Rectangular Area in a Histogram in Java

Continuous bars should be used to form the largest possible rectangle. We'll assume in the interest of convenience that each bar's width is 1. Naive Approach In this method, each bar will be...

6 minutes read.

How to use Lambda Expression in Java?

The new and significant lambda expression feature of Java was added in Java SE 8. It provides a clear and concise mechanism for describing a single method interface using an...

4 minutes read.

Convert JSON to Map in Java

JACKSON and GSON libraries are two extremely capable JSON-related libraries offered by Java. To efficiently work with the returned JSON data, we frequently need to convert JSON responses into a...

6 minutes read.