Java,在Try-Catch之后继续

时间:2017-08-13 16:05:51

标签: 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");
        }
    }
}

4 个答案:

答案 0 :(得分: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");
    }
}

我尝试使我的异常更具体,避免使用过于宽泛的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);
    }
}

答案 1 :(得分:2)

如果发生异常,则无法返回,但是我们可以处理异常并继续下一次迭代,或者如果条件在分割之前添加如下:

**if(numbers[i] != 0){**
division = new testing(100/numbers[i]);

或将try catch放入for循环中。

答案 2 :(得分:1)

将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(Exception e){
      System.out.println("A number cannot be divided by 0");
   }
  }

答案 3 :(得分:0)

更新代码:在代码中添加了一个try catch:

public class testing {

  int[] table;
  int number;

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

  public static void main(String[] args) {
    int[] numbers = { 2, 3, 0, 4, 5 };
    testing division;

    for (int i = 0; i < 5; i++) {
      try {
        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");
      }
    }
  }
}