读取输入并在方法中执行所需的计算。将导致异常的代码保留在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