Create a try block that can generate three types of exceptions and handle them with multiple catch blocks

Long Answer
Views 29

Answer:


public class MultiExceptionDemo {
    public static void main(String args[]) {
        try {
            // 1. ArithmeticException
            int a = 10 / 0;

            // 2. NullPointerException
            String str = null;
            System.out.println(str.length());

            // 3. ArrayIndexOutOfBoundsException
            int[] arr = new int[3];
            arr[5] = 100;
        }
        catch (ArithmeticException e) {
            System.out.println("Arithmetic Exception: " + e.getMessage());
        }
        catch (NullPointerException e) {
            System.out.println("Null Pointer Exception: " + e.getMessage());
        }
        catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Array Index Out Of Bounds Exception: " + e.getMessage());
        }
        catch (Exception e) {
            System.out.println("General Exception: " + e.getMessage());
        }
    }
}

Output (first exception occurs):

Arithmetic Exception: / by zero

Note: Execution stops at the first exception, remaining code in try block is skipped.

Related Articles:

This section is dedicated exclusively to Questions & Answers. For an in-depth exploration of Java Programming Language, click the links and dive deeper into this subject.

Join Our telegram group to ask Questions

Click below button to join our groups.