Java Examples - Handling Multiple Exceptions (Multiple catch)
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 exception declared by the other party, there should be a corresponding catch block. If exceptions in multiple catch blocks have an inheritance relationship, place the parent exception catch block at the bottom.
The following example demonstrates how to handle multiple exceptions:
ExceptionDemo.java file
class Demo
{
int div(int a,int b) throws ArithmeticException,ArrayIndexOutOfBoundsException//Functionally, use the throws keyword to declare that this function may encounter problems.
{
int []arr = new int [a];
System.out.println(arr[4]);//The first exception created
return a/b;//The 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 the 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)//The parent class is written here to catch other unexpected exceptions; it can only be written after the child class exception code.
//However, in general it is not written.
{
System.out.println(e.toString());
}
System.out.println("Over");
}
}
The above code produces the following output:
java.lang.ArrayIndexOutOfBoundsException: 4 OverOther Extensions
Java Examples