How to catch multiple exceptions in the same catch clause with Java

2 Answers

0 votes
public class MyClass {
    public static void main(String args[]) {
        try {
            int[] arr = {1, 2, 3, 4, 5, 6, 7};
               
            arr[19] = 938;
           
        } catch (ArrayIndexOutOfBoundsException | ArithmeticException e) {
            System.out.println("Exception: " + e);
        }
    }
}
 
 
 
 
/*
run:

Exception: java.lang.ArrayIndexOutOfBoundsException: Index 19 out of bounds for length 7

*/

 



answered Oct 25, 2023 by avibootz
0 votes
public class MyClass {
    public static void main(String args[]) {
        try {
            int[] arr = {1, 2, 3, 4, 5, 6, 7};
               
            arr[19] = 938;
           
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Exception 1: " + e);
        } catch (ArithmeticException e) {
            System.out.println("Exception 2: " + e);
        }
    }
}
 
 
 
 
/*
run:

Exception 1: java.lang.ArrayIndexOutOfBoundsException: Index 19 out of bounds for length 7

*/

 



answered Oct 25, 2023 by avibootz

Related questions

1 answer 212 views
1 answer 194 views
194 views asked Dec 17, 2016 by avibootz
1 answer 168 views
4 answers 336 views
1 answer 130 views
130 views asked Jan 24, 2024 by avibootz
1 answer 248 views
1 answer 97 views
...