Java,在Try-Catch之后继续

mar*_*ark -4 java try-catch

当我运行程序时,100除以数字,但一旦达到0,就会出现一条消息告诉用户100不能除以0.

如何在错误发生后让程序继续运行,并将100除以其余数字.

这是我目前的代码:

public class testing {
    int[] table;
    int number;

    public testing(int number) {
        this.number = number;
        table = new int[number];
    }

    public static void main(String[] args) {
        try {
            int[] numbers = { 2, 3, 0, 4, 5 };
            testing division;
            for (int i = 0; i < 5; i++) {
                division = new testing(100 / numbers[i]);
                System.out.println("Answer is " + division.number);
            }
        } catch (Exception e) {
            System.out.println("A number cannot be divided by 0");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Hov*_*els 5

您可以简单地将try/catch设置为更精细的比例 - 将其放在 for循环中.

for (int i = 0; i < 5; i++) {
    try {
        division = new testing(100 / numbers[i]);
        System.out.println("Answer is " + division.number);
    } catch (ArithmeticException e) { // avoid catching with the overly broad Exception 
        System.out.println("A number cannot be divided by 0");
    }
}
Run Code Online (Sandbox Code Playgroud)

我尝试使我的异常更具体,并避免使用过于宽泛的Exception类,这里使用ArithmeticException.

但更重要的是,我完全摆脱了try catch,只需测试0就可以完全避免异常.

for (int i = 0; i < 5; i++) {
    if (numbers[i] == 0) {
        System.out.println("A number cannot be divided by 0");
    } else {
        division = new testing(100 / numbers[i]);
        System.out.println("Answer is " + division.number);
    }
}
Run Code Online (Sandbox Code Playgroud)