在 Java 中抛出异常后如何循环程序?

java 8object oriented programmingprogramming更新于 2025/9/21 8:44:17

读取输入并在方法中执行所需的计算。将导致异常的代码保留在 try 块中,并在 catch 块中捕获所有可能的异常。在每个 catch 块中显示相应的消息并再次调用该方法。

示例

在下面的例子中,我们有一个包含 5 个元素的数组,我们从用户那里接受两个表示数组中位置的整数并对它们执行除法运算,如果输入的表示位置的整数大于 5(异常的长度),则会发生 ArrayIndexOutOfBoundsException,如果分母选择的位置是 4,即 0,则会发生 ArithmeticException。

我们正在读取值并在静态方法中计算结果。我们在两个 catch 块中捕获这两个异常,并且在每个块中,我们都在显示相应的消息后调用该方法。

import java.util.Arrays;
import java.util.Scanner;
public class LoopBack {
   int[] arr = {10, 20, 30, 2, 0, 8};
   public static void getInputs(int[] arr){
      Scanner sc = new Scanner(System.in);
      System.out.println("Choose numerator and denominator(not 0) from this array (enter positions 0 to 5)");
      int a = sc.nextInt();
      int b = sc.nextInt();
      try {
         int result = (arr[a])/(arr[b]);
         System.out.println("Result of "+arr[a]+"/"+arr[b]+": "+result);
      }catch(ArrayIndexOutOfBoundsException e) {
         System.out.println("Error: You have chosen position which is not in the array: TRY AGAIN");
         getInputs(arr);
      }catch(ArithmeticException e) {
         System.out.println("Error: Denominator must not be zero: TRY AGAIN");
         getInputs(arr);
      }
   }
   public static void main(String [] args) {
      LoopBack obj = new LoopBack();
      System.out.println("Array: "+Arrays.toString(obj.arr));
      getInputs(obj.arr);
   }
}

输出

Array: [10, 20, 30, 2, 0, 8]
Choose numerator and denominator(not 0) from this array (enter positions 0 to 5)
14
24
Error: You have chosen position which is not in the array: TRY AGAIN
Choose numerator and denominator(not 0) from this array (enter positions 0 to 5)
3
4
Error: Denominator must not be zero: TRY AGAIN
Choose numerator and denominator(not 0) from this array (enter positions 0 to 5)
0
3
Result of 10/2: 5

相关文章