Programming Pandit

c/c++/c#/Javav/Python


Latest Update

Tuesday, March 11, 2025

Exceptions, exception hierarchy in Java

 

Exceptions and Exception Hierarchy in Java


📌 What are Exceptions?

An exception is an event that disrupts the normal flow of a program during execution. In Java, exceptions are objects that describe an error or unexpected behavior occurring during runtime.


📌 Why Use Exceptions?

  1. Improved Code Readability: Handles errors using separate code blocks.
  2. Separation of Error Handling Code: Keeps the main logic clean.
  3. Controlled Error Handling: Allows the program to gracefully recover from unexpected events.

📌 Exception Hierarchy in Java

All exceptions in Java are subclasses of the Throwable class, which is the superclass for all errors and exceptions.

🔍 Structure:

                 Throwable

                /         \

            Error         Exception

                           /      \

                Checked Exceptions  Unchecked Exceptions

                                    (RuntimeException)


📌 Types of Exceptions

1. Checked Exceptions (Compile-time Exceptions)

These exceptions are checked at compile time. If not handled, the compiler will throw an error.
Examples:

  • IOException
  • SQLException
  • ClassNotFoundException

Example Code:

import java.io.*;

 

public class CheckedExample {

    public static void main(String[] args) {

        try {

            FileInputStream file = new FileInputStream("nonexistentfile.txt");

        } catch (FileNotFoundException e) {

            System.out.println("File not found exception caught!");

        }

    }

}


2. Unchecked Exceptions (Runtime Exceptions)

These exceptions occur at runtime and are not checked during compilation.
Examples:

  • NullPointerException
  • ArrayIndexOutOfBoundsException
  • ArithmeticException

Example Code:

public class UncheckedExample {

    public static void main(String[] args) {

        int[] arr = new int[3];

        try {

            System.out.println(arr[5]); // ArrayIndexOutOfBoundsException

        } catch (ArrayIndexOutOfBoundsException e) {

            System.out.println("Array index out of bounds exception caught!");

        }

    }

}


3. Errors

Errors are severe issues that a program usually cannot recover from.
Examples:

  • OutOfMemoryError
  • StackOverflowError
  • VirtualMachineError

Example Code:

public class ErrorExample {

    public static void recursiveMethod() {

        recursiveMethod();  // Infinite recursion causing StackOverflowError

    }

 

    public static void main(String[] args) {

        recursiveMethod();

    }

}


📌 Exception Class Hierarchy (Important Classes)

  • Throwable (Superclass for all exceptions and errors)
    • Exception (General superclass for recoverable exceptions)
      • Checked Exceptions (Require handling)
        • IOException
        • SQLException
        • FileNotFoundException
      • Unchecked Exceptions (RuntimeExceptions, not compulsory to handle)
        • ArithmeticException
        • NullPointerException
        • IndexOutOfBoundsException
    • Error (Serious problems not meant to be caught by applications)
      • OutOfMemoryError
      • StackOverflowError
      • VirtualMachineError

📌 Common Exception Methods

public String getMessage()       // Returns detailed message about the exception.

public String toString()          // Returns a short description of the exception.

public void printStackTrace()     // Prints the stack trace to the console.


📌 Creating a Custom Exception

class CustomException extends Exception {

    public CustomException(String message) {

        super(message);

    }

}

 

public class CustomExceptionDemo {

    public static void main(String[] args) {

        try {

            throw new CustomException("This is a custom exception!");

        } catch (CustomException e) {

            System.out.println(e.getMessage());

        }

    }

}


📌 Key Points to Remember

  1. Checked Exceptions: Must be handled using try-catch or declared using throws.
  2. Unchecked Exceptions: Can be handled, but not mandatory.
  3. Errors: Critical issues; typically not caught by the application.
  4. Custom Exceptions: Useful for specific error handling in your application.

 

No comments:

Post a Comment