如何在 Java 中异常抛出后循环执行程序?
在某个方法内读取输入并执行必需的计算。将导致异常的代码放在 try 块内,并在 catch 块中捕获所有可能的异常。在各个 catch 块中,显示相应的消息并再次调用该方法。
示例
以下示例中,我们使用了一个包含 5 个元素的数组,接受来自用户代表数组位置的两个整数,并对它们执行除法操作,如果输入的代表位置的整数大于 5(异常长度),则发生 ArrayIndexOutOfBoundsException,如果为分母选择的 0 位置为 4,则发生 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
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP