1

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

4

2 回答 2

4

除了之外ArithmeticException,没有共同的父母。在这一块ArrayIndexOutOfBoundsExceptionException

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

e得到一个静态类型,这是ExceptionRuntimeException. 有了这个,就CustomException(Exception e, int num)被称为。

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

于 2016-06-01T13:49:48.640 回答
3

该行为在JLS Sec 14.20中通过这个不太突出的句子定义:

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

lub表示“最小上限”,在JLS Sec 4.10.4中定义:

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

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

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

于 2016-06-01T13:57:38.350 回答