gpt4 book ai didi

java - 无法解析 Multi catch 中的异常类

转载 作者:行者123 更新时间:2023-11-29 06:30:04 24 4
gpt4 key购买 nike

我正在使用 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 没有共同的父级。在这一 block 中

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

e 得到一个静态类型,这就是ExceptionRuntimeException。这样,调用了 CustomException(Exception e, int num)

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

关于java - 无法解析 Multi catch 中的异常类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37570431/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com