Home / Questions / Create a try block that can generate three types of exceptions and handle them with multiple catch blocks
Explanatory Question

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

👁 31 Views
📘 Detailed Answer
🕒 Easy to Read
Read the answer carefully and go through the related questions on the right side to improve your understanding of this topic.

Answer with Explanation


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.