我想以更具體的方式處理NumberFormatException。發生 此異常,當它試圖分配什麼,但一個整數,輸入以下時:如何以更具體的方式處理NumberFormatException?
- 串
- 字符
- 空輸入
- 雙號
根據什麼被輸入我想顯示一個適當的消息,如
你輸入的字符串,請輸入整數
或
值不能爲空,請輸入一個整數值
下面的代碼捕獲NumberFormatException
一般辦法。
我不知道是否有辦法包含更多的catch子句。
import java.util.Scanner;
public class TestException {
static int input;
static Scanner scan = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("Enter an integer number: ");
try {
input = Integer.parseInt(scan.next());
System.out.println("You've entered number: " + input);
} catch (NumberFormatException e) {
System.out.println("You've entered non-integer number");
System.out.println("This caused " + e);
}
}
}
類似的線就顯示「你已進入空白或非數字值,請再試一次「??這是更好的嗎? –
您可以分析catch子句中的給定輸入,顯然沒有內置邏輯來確定各種任意原因爲什麼字符串作爲數字無效 – Esailija
也終止帶有錯誤代碼的進程。 System.exit(1); –