如何在 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