我正在使用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
之外,没有共同的父级ArithmeticException
和ArrayIndexOutOfBoundsException
。在这一块中
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"是比任何其他共享超类型更具体的共享超类型(即,没有其他共享超类型是最小上限的子类型)。
在您的情况下,ArithmeticException
和 ArrayIndexOutOfBoundsException
的lub
是RuntimeException
,因此将Exception
作为参数类型的重载是可以调用的最具体的方法。
请记住,是编译器决定要调用的重载:它不是在运行时决定的。