Easy Tutorial
❮ Java Hashmap Putifabsent File Read ❯

Java Example - Chained Exceptions

Java Examples

The following example demonstrates the use of multiple catch blocks to handle chained exceptions:

Main.java File

public class Main {
    public static void main (String args[]) throws Exception {
        int n = 20, result = 0;
        try {
            result = n / 0;
            System.out.println("The result is " + result);
        } catch (ArithmeticException ex) {
            System.out.println("Arithmetic exception occurred: " + ex);
            try {
                throw new NumberFormatException();
            } catch (NumberFormatException ex1) {
                System.out.println("Manually thrown chained exception: " + ex1);
            }
        }
    }
}

The output of the above code is:

Arithmetic exception occurred: java.lang.ArithmeticException: / by zero
Manually thrown chained exception: java.lang.NumberFormatException

Java Examples

❮ Java Hashmap Putifabsent File Read ❯