无法解析 Multi catch 中的异常类



我正在使用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并使其引发所需的异常。

除了

Exception之外,没有共同的父级ArithmeticExceptionArrayIndexOutOfBoundsException。在这一块中

catch(ArithmeticException|ArrayIndexOutOfBoundsException e){
    throw new CustomException(e, num);
}

e得到一个静态类型,这是

Exception RuntimeException。有了这个,CustomException(Exception e, int num)就被称为。

如果将它们拆分,e具有更专用的类型。

JLS Sec 14.20 中通过以下不太突出的句子定义了该行为:

异常参数的声明类型表示为与替代D1 | D2 | ... | Dn的联合,lub(D1, D2, ..., Dn)

lub的意思是JLS Sec 4.10.4中定义的"最小上限":

一组引用类型的最小上限或"lub"是比任何其他共享超类型更具体的共享超类型(即,没有其他共享超类型是最小上限的子类型)。

在您的情况下,ArithmeticExceptionArrayIndexOutOfBoundsExceptionlubRuntimeException ,因此将Exception作为参数类型的重载是可以调用的最具体的方法。

请记住,是编译器决定要调用的重载:它不是在运行时决定的。

最新更新