我正在使用 multicatch(Java 7 及更高版本)创建一个自定义异常类。这是我创建的类。请参考以下代码:
public class CustomException extends Exception{
public CustomException() {
System.out.println("Default Constructor");
}
public CustomException(ArithmeticException e, int num){
System.out.println("Divison by ZERO! is attempted!!! Not defined.");
}
public CustomException(ArrayIndexOutOfBoundsException e, int num){
System.out.println("Array Overflow!!!");
}
public CustomException(Exception e, int num){
System.out.println("Error");
}
上面的类由下面的类扩展。
import java.util.Scanner;
public class ImplementCustomException extends CustomException {
public static void main(String[] args) throws CustomException {
int num = 0;
System.out.println("Enter a number: ");
try(Scanner in = new Scanner(System.in);){
num = in.nextInt();
int a = 35/num;
int c[] = { 1 };
c[42] = 99;
}
catch(ArithmeticException|ArrayIndexOutOfBoundsException e){
throw new CustomException(e, num);
}
}
}
每次我尝试运行它时,它都会调用相同的构造函数,即带有“异常”的构造函数。为什么会这样?
但是,如果我将 multi-catch 语法替换为以下代码。它按预期工作。
catch(ArithmeticException ex){
CustomException e = new CustomException(ex, num);
throw e;
}
catch(ArrayIndexOutOfBoundsException ex){
CustomException e = new CustomException(ex, num);
throw e;
}
请协助我进行可能的更改,以便使用 multi catch 并使其抛出所需的异常。