Exception Hierarchy
# Java Example - Multiple Exception Handling (Multiple Catch)
[ Java Example](#)
Handling exceptions:
1. When declaring exceptions, it is recommended to declare more specific exceptions so that they can be handled more specifically.
2. For each declared exception, there should be a corresponding catch block. If there is an inheritance relationship among the exceptions in multiple catch blocks, the catch block for the parent class exception should be placed at the end.
The following example demonstrates how to handle multiple exceptions:
## ExceptionDemo.java File
class Demo{int div(int a,int b)throws ArithmeticException,ArrayIndexOutOfBoundsException//Declare that this function may have problems using the throws keyword {int[]arr = new int; System.out.println(arr);//First exception created return a/b;//Second exception created }}class ExceptionDemo{public static void main(String[]args)//throws Exception {Demo d = new Demo(); try{int x = d.div(4,0);//The three sets of examples in the program running screenshot correspond to these three lines of code here //int x = d.div(5,0); //int x = d.div(4,1); System.out.println("x="+x); }catch(ArithmeticException e){System.out.println(e.toString()); }catch(ArrayIndexOutOfBoundsException e){System.out.println(e.toString()); }catch(Exception e)//Parent class, written here to catch other unexpected exceptions, can only be written after the code for subclass exceptions //But generally it is not written {System.out.println(e.toString()); }System.out.println("Over"); }}
The output of the above code is:
java.lang.ArrayIndexOutOfBoundsException: 4Over
[ Java Example](#)
YouTip