EZ

Eduzan

Learning Hub

Eduzan
Eduzan / Java

Exception

Exception Handling in Java is one of the effective means to manage runtime errors and preserve the regular flow of the application. Java’s mechanism for handling runtime errors like ClassNotFoundExceptionIOExceptionSQLException, and RemoteException ensures that exceptions are caught and handled appropriately.

What are Java Exceptions?

In Java, an Exception is an unwanted or unexpected event that occurs during the execution of a program, i.e., at runtime, which disrupts the normal flow of the program. Java provides mechanisms to catch and handle exceptions using the try-catch block. When an exception occurs, an exception object is created, containing information such as the name, description, and the program state at the time the exception occurred.

Major Reasons for Exceptions:

  • Invalid user input
  • Device failure
  • Loss of network connection
  • Out of disk memory
  • Code errors
  • Array index out of bounds
  • Null reference
  • Type mismatch
  • Attempt to open an unavailable file
  • Database errors
  • Arithmetic errors (e.g., division by zero)

Errors like memory leaksstack overflow, and out of memory are irrecoverable conditions typically beyond the control of the programmer. Errors should not be handled.

Difference between Error and Exception:

  • Error: Represents a serious problem that the application should not attempt to catch.
  • Exception: Indicates a condition that a reasonable application might attempt to catch and handle.

Exception Hierarchy

In Java, all exceptions and errors are subclasses of the Throwable class. The two branches are:

  • Exception: User-defined and built-in exceptions such as NullPointerException.
  • Error: System-level errors like StackOverflowError, indicating issues with the JVM.

Types of Exceptions

1. Built-in Exceptions: Java has a wide range of built-in exceptions divided into two categories:

  • Checked Exceptions: These exceptions are checked at compile-time. Examples include IOExceptionSQLException.
  • Unchecked Exceptions: These exceptions occur at runtime and are not checked during compilation. Examples include ArrayIndexOutOfBoundsException and NullPointerException.

2. User-Defined Exceptions: When built-in exceptions do not adequately describe an issue, Java allows for the creation of custom exceptions.

Example of Exception Handling Methods:

1. printStackTrace() Prints the name, description, and stack trace of the exception.

public class Main {
    public static void main(String[] args) {
        try {
            int a = 5;
            int b = 0;
            System.out.println(a / b);
        } catch (ArithmeticException e) {
            e.printStackTrace();
        }
    }
}

Output:

java.lang.ArithmeticException: / by zero
at Main.main(Main.java:5)

2. toString() Prints the name and description of the exception.

public class Main {
    public static void main(String[] args) {
        try {
            int a = 5;
            int b = 0;
            System.out.println(a / b);
        } catch (ArithmeticException e) {
            System.out.println(e.toString());
        }
    }
}

Output:

java.lang.ArithmeticException: / by zero

3. getMessage() Prints only the description of the exception.

public class Main {
    public static void main(String[] args) {
        try {
            int a = 5;
            int b = 0;
            System.out.println(a / b);
        } catch (ArithmeticException e) {
            System.out.println(e.getMessage());
        }
    }
}

Output:

/ by zero

JVM Exception Handling Flow

When an exception occurs in a method, the method creates an Exception Object and passes it to the JVM. The JVM looks for an appropriate exception handler in the call stack, starting with the method where the exception occurred and moving backward. If no handler is found, the default exception handler terminates the program and prints the exception details.

Example of JVM Handling:

public class Main {
    public static void main(String[] args) {
        String str = null;
        System.out.println(str.length()); // NullPointerException
    }
}

Output:

Exception in thread "main" java.lang.NullPointerException
at Main.main(Main.java:4)

Programmer Handling Exception with Custom Code:

Using trycatchfinallythrow, and throws, Java allows programmers to handle exceptions gracefully.

Example:

public class Main {
    static int divideByZero(int a, int b) {
        return a / b;  // ArithmeticException if b is 0
    }

    static int computeDivision(int a, int b) {
        try {
            return divideByZero(a, b);
        } catch (NumberFormatException e) {
            System.out.println("NumberFormatException occurred");
            return 0;
        }
    }

    public static void main(String[] args) {
        try {
            int result = computeDivision(10, 0);
            System.out.println("Result: " + result);
        } catch (ArithmeticException e) {
            System.out.println("Error: " + e.getMessage());
        }
    }
}

Output:

Error: / by zero

Try-Catch Clause Usage Example:

public class Main {
    public static void main(String[] args) {
        int[] arr = new int[4];
        try {
            int value = arr[4]; // This will throw ArrayIndexOutOfBoundsException
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Array index is out of bounds.");
        }
        System.out.println("Program continues...");
    }
}

Output:

Array index is out of bounds.
Program continues...
End of lesson.