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

Exception Propagation in Java with examples

By Chaitanya Singh | Filed Under: java

Exception Propagation in Java

Exception propagation is a process by which compiler ensures that the exception is handled somewhere, if it is not handled where the exception occurs. For example, if main() method calls a method and that method (method1) is calling another method (method2). If the exception occurs in method2 and is not handled there then the exception is propagated to calling method method1 to see if it is handled there.

Exception Propagation Program in Java

This program demonstrates how the exception propagation happens in Java. Here, in the main method, we are calling a method to print the quotient value after dividing an integer num1 by num2.

The printQuotient() method internally calling another method calculateQuotient() to calculate the quotient value.

Since the value of variable num2 is 0 the exception occurs where the division actually happens, in this case, it happens in the calculateQuotient() method.

However there is no exception handling in calculateQuotient() method, so the exception is automatically propagated to the calling method printQuotient(), where the exception is handled.

public class JavaExample {

  //exception occurred in this method but it is not handled here
  //so the exception is propagated to the calling method printQuotient
  int calculateQuotient(int num1, int num2) {
    int temp = num1/num2;
    return temp;
  }

  //Here we have done exception handling
  void printQuotient(int num1, int num2){
    try {
      int q = calculateQuotient(num1, num2);
      System.out.println("Quotient is: " + q);
    }catch(ArithmeticException e){
      System.out.println("Arithmetic exception occurred");
    }
  }
  public static void main(String[] args) {

    int num1 = 10, num2 = 0;

    //calling method
    JavaExample obj = new JavaExample();
    obj.printQuotient(num1, num2);

  }
}

Output:

Arithmetic exception occurred

How can we use this feature to improve the code?

In any java application, there are multiple scenarios where a method calls second method and the second method calls third method. As we have seen that how exceptions are propagated in the hierarchy of method calling, so you only need do exception handling in the first method, this saves the exception handling part in second and third method.

You do not need to write addition code in second and third methods, this saves time, shorten the lines of code and improves the readability of the code.

Note: This doesn’t mean that the exception handling cannot be done in the methods down in the method calling chain, it can be done there, but doing so will make code look cluttered. Also, it will make the code harder to troubleshoot in case of any issue arises.

Exception propagation in checked and unchecked exceptions

Does exception propagation happens in both checked and unchecked exceptions? No, exception propagation only happens in unchecked exceptions and not in checked exceptions. The reason is pretty simple, the checked exceptions required to be handled during compile time else the compiler will throw compilation error.

This program throws compilation error because the exception is not handled in myMethod3().

class JavaExample{
  void myMethod3(){
    throw new java.io.IOException("Checked Exception");
  }
  void myMethod2(){
    myMethod3();
  }
  void myMethod(){
    try{
      myMethod2();
    }catch(Exception e){
      System.out.println("Exception occurred: "+e);
    }
  }
  public static void main(String args[]){
    JavaExample obj=new JavaExample();
    obj.myMethod();
    System.out.println("normal flow");
  }
}

Output:

Error:(3, 5) java: unreported exception java.io.IOException; must 
be caught or declared to be thrown

Recommended Posts

  • Checked and Unchecked exceptions in Java
  • Exception handling in Method Overriding
  • User defined exception in Java
  • throw keyword in Java with Example
❮ PreviousNext ❯

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 – 2022 BeginnersBook . Privacy Policy . Sitemap