Skip to main content

Command Palette

Search for a command to run...

Understanding How an Exception Occurs Internally in Java

Updated
โ€ข4 min read
Understanding How an Exception Occurs Internally in Java
N

I am a Tech Enthusiast having 13+ years of experience in ๐ˆ๐“ as a ๐‚๐จ๐ง๐ฌ๐ฎ๐ฅ๐ญ๐š๐ง๐ญ, ๐‚๐จ๐ซ๐ฉ๐จ๐ซ๐š๐ญ๐ž ๐“๐ซ๐š๐ข๐ง๐ž๐ซ, ๐Œ๐ž๐ง๐ญ๐จ๐ซ, with 12+ years in training and mentoring in ๐’๐จ๐Ÿ๐ญ๐ฐ๐š๐ซ๐ž ๐„๐ง๐ ๐ข๐ง๐ž๐ž๐ซ๐ข๐ง๐ , ๐ƒ๐š๐ญ๐š ๐„๐ง๐ ๐ข๐ง๐ž๐ž๐ซ๐ข๐ง๐ , ๐“๐ž๐ฌ๐ญ ๐€๐ฎ๐ญ๐จ๐ฆ๐š๐ญ๐ข๐จ๐ง ๐š๐ง๐ ๐ƒ๐š๐ญ๐š ๐’๐œ๐ข๐ž๐ง๐œ๐ž. I have ๐’•๐’“๐’‚๐’Š๐’๐’†๐’… ๐’Ž๐’๐’“๐’† ๐’•๐’‰๐’‚๐’ 10,000+ ๐‘ฐ๐‘ป ๐‘ท๐’“๐’๐’‡๐’†๐’”๐’”๐’Š๐’๐’๐’‚๐’๐’” and ๐’„๐’๐’๐’…๐’–๐’„๐’•๐’†๐’… ๐’Ž๐’๐’“๐’† ๐’•๐’‰๐’‚๐’ 500+ ๐’•๐’“๐’‚๐’Š๐’๐’Š๐’๐’ˆ ๐’”๐’†๐’”๐’”๐’Š๐’๐’๐’” in the areas of ๐’๐จ๐Ÿ๐ญ๐ฐ๐š๐ซ๐ž ๐ƒ๐ž๐ฏ๐ž๐ฅ๐จ๐ฉ๐ฆ๐ž๐ง๐ญ, ๐ƒ๐š๐ญ๐š ๐„๐ง๐ ๐ข๐ง๐ž๐ž๐ซ๐ข๐ง๐ , ๐‚๐ฅ๐จ๐ฎ๐, ๐ƒ๐š๐ญ๐š ๐€๐ง๐š๐ฅ๐ฒ๐ฌ๐ข๐ฌ, ๐ƒ๐š๐ญ๐š ๐•๐ข๐ฌ๐ฎ๐š๐ฅ๐ข๐ณ๐š๐ญ๐ข๐จ๐ง๐ฌ, ๐€๐ซ๐ญ๐ข๐Ÿ๐ข๐œ๐ข๐š๐ฅ ๐ˆ๐ง๐ญ๐ž๐ฅ๐ฅ๐ข๐ ๐ž๐ง๐œ๐ž ๐š๐ง๐ ๐Œ๐š๐œ๐ก๐ข๐ง๐ž ๐‹๐ž๐š๐ซ๐ง๐ข๐ง๐ . I am interested in ๐ฐ๐ซ๐ข๐ญ๐ข๐ง๐  ๐›๐ฅ๐จ๐ ๐ฌ, ๐ฌ๐ก๐š๐ซ๐ข๐ง๐  ๐ญ๐ž๐œ๐ก๐ง๐ข๐œ๐š๐ฅ ๐ค๐ง๐จ๐ฐ๐ฅ๐ž๐๐ ๐ž, ๐ฌ๐จ๐ฅ๐ฏ๐ข๐ง๐  ๐ญ๐ž๐œ๐ก๐ง๐ข๐œ๐š๐ฅ ๐ข๐ฌ๐ฌ๐ฎ๐ž๐ฌ, ๐ซ๐ž๐š๐๐ข๐ง๐  ๐š๐ง๐ ๐ฅ๐ž๐š๐ซ๐ง๐ข๐ง๐  new subjects.

Introduction

Exceptions in Java occur when the Java runtime system encounters an error while executing a program. When an error occurs, Java generates an exception object, which contains information about the error. This process involves multiple layers of the Java runtime environment (JRE) and Java Virtual Machine (JVM).

This document explains the internal mechanism of exception handling in Java and how exceptions propagate through the Java system.

Example: Exception Occurrence in Java

Consider the following Java program that performs division:

import java.util.Scanner;

public class ExceptionDemo {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        System.out.println("Enter Dividend:");
        int dividend = input.nextInt();

        System.out.println("Enter Divisor:");
        int divisor = input.nextInt();

        int result = dividend / divisor; // Exception may occur here

        System.out.println(dividend + "/" + divisor + " = " + result);
        System.out.println("I will be happy if I get executed");
    }
}

Output when a valid divisor is entered:

Enter Dividend:
10
Enter Divisor:
2
10/2 = 5
I will be happy if I get executed

Output when the divisor is zero:

Enter Dividend:
10
Enter Divisor:
0
Exception in thread "main" java.lang.ArithmeticException: / by zero
    at ExceptionDemo.main(ExceptionDemo.java:10)

In this case, Java detects the attempt to divide by zero and throws an ArithmeticException, terminating the program execution.

Internal Flow of Exception Handling in Java

Step-by-Step Breakdown of Exception Occurrence and Handling:

Step 1: Invalid Input Provided by User

When a user provides invalid input (e.g., entering 0 as a divisor), Java detects an error at runtime.

Step 2: JVM Contacts the JRE

Since the program cannot continue execution with an invalid input, the JVM contacts the Java Runtime Environment (JRE) to handle the issue.

Step 3: JRE Consults java.lang.Throwable

The JRE then interacts with the java.lang.Throwable class to determine the type of exception.

Step 4: Exception Type Determination

The Throwable class decides whether the error falls under:

  • Checked Exceptions (Synchronous exceptions that must be handled explicitly)

  • Unchecked Exceptions (Runtime exceptions like NullPointerException, ArithmeticException, etc.)

  • Errors (System-level errors like StackOverflowError, OutOfMemoryError)

Step 5: JRE Contacts Java Exception API

Once the type of exception is determined, the JRE communicates with the Java Exception API to obtain an appropriate exception subclass.

Step 6: JVM Creates an Exception Object

The JVM then creates an instance of the corresponding exception subclass. For example, in the case of division by zero, an ArithmeticException object is instantiated.

Step 7: JVM Generates System Error Messages

After creating the exception object, the JVM prints a system error message on the console, which looks something like this:

Exception in thread "main" java.lang.ArithmeticException: / by zero
    at ExceptionDemo.main(ExceptionDemo.java:10)

Handling the Exception (If Implemented)

If the program includes exception handling using try-catch, the error can be caught, and a user-friendly message can be displayed instead of a system error.

Handling the Exception Using try-catch

import java.util.Scanner;

public class ExceptionHandlingDemo {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        System.out.println("Enter Dividend:");
        int dividend = input.nextInt();

        System.out.println("Enter Divisor:");
        int divisor = input.nextInt();

        try {
            int result = dividend / divisor; // Exception handled here
            System.out.println(dividend + "/" + divisor + " = " + result);
        } catch (ArithmeticException e) {
            System.out.println("Error: Cannot divide by zero. Please enter a valid divisor.");
        }

        System.out.println("Program execution completed successfully.");
    }
}

Output when divisor is zero:

Enter Dividend:
10
Enter Divisor:
0
Error: Cannot divide by zero. Please enter a valid divisor.
Program execution completed successfully.

The program now continues execution instead of crashing.

Exception Handling in JVM

Key Components Involved in Exception Handling:

  1. JVM (Java Virtual Machine): Detects the exception and creates an exception object.

  2. JRE (Java Runtime Environment): Determines the type of exception.

  3. Java Exception API: Provides the appropriate exception subclass.

  4. Programmer: Converts system error messages into user-friendly messages using try-catch.

Hierarchy of Java Exception Handling

java.lang.Throwable
   โ”œโ”€โ”€ java.lang.Error
   โ”‚     โ”œโ”€โ”€ StackOverflowError
   โ”‚     โ”œโ”€โ”€ OutOfMemoryError
   โ”‚
   โ”œโ”€โ”€ java.lang.Exception
         โ”œโ”€โ”€ IOException (Checked Exception)
         โ”œโ”€โ”€ SQLException (Checked Exception)
         โ”œโ”€โ”€ ArithmeticException (Unchecked Exception)
         โ”œโ”€โ”€ NullPointerException (Unchecked Exception)

5. Conclusion

  • When an exception occurs, the JVM, JRE, and Java Exception API work together to determine and throw the appropriate exception.

  • Unchecked exceptions (like ArithmeticException) terminate program execution if not handled.

  • Handling exceptions with try-catch ensures user-friendly messages and prevents crashes.

  • It is recommended for Java programmers to handle exceptions properly to avoid abrupt program termination.

By understanding how exceptions occur internally, Java developers can write more robust and fault-tolerant programs.


More from this blog

Naveen P.N's Tech Blog

95 posts