我使用try catch寫的程式捕獲異常,卻無法捕獲?

2013-03-24 7:02 am
這段程式是我寫的是一個用try catch進行異常捕獲。但我發覺。我似乎只能捕獲算數運算異常,無法捕獲輸入格式異常
package exceptionDemo;

import java.util.Scanner;

public class ExceptionDemo01 {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
try{

Scanner scanner=new Scanner(System.in);
System.out.println("請輸入數位");
int num=scanner.nextInt();
System.out.println("請輸入數位");
int num2=scanner.nextInt();
int temp=num/num2;
System.out.println("獲得結果"+temp);
}
catch (ArithmeticException e) {
// TODO: handle exception
System.out.println("算數運算異常:————"+e);
}

catch (NumberFormatException e) {
// TODO: handle exception
System.out.println("輸入格式異常:——————"+e);

}
catch (ArrayIndexOutOfBoundsException e) {
// TODO: handle exception
System.out.println("沒有輸入參數或者輸入參數數目錯誤"+e);
}
finally{
System.out.println("執行此代碼");
}
}


}
這是運行捕獲算數運算異常(即輸入一個除數為1,被除數書為0)
請輸入數位
1
請輸入數位
0
算數運算異常:————java.lang.ArithmeticException: / by zero
執行此代碼
但我希望捕獲輸入格式異常卻不行.,我第一次輸入1,第二次輸入a就直接運行錯誤,無法被捕獲
請輸入數位
1
請輸入數位
a
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:840)
at java.util.Scanner.next(Scanner.java:1461)
at java.util.Scanner.nextInt(Scanner.java:2091)
at java.util.Scanner.nextInt(Scanner.java:2050)
at exceptionDemo.ExceptionDemo01.main(ExceptionDemo01.java:18)
執行此代碼

回答 (1)

2013-03-24 10:45 am
✔ 最佳答案


為何捉不到例外?

我想應該是

因為預期接收到的類型與實際輸入類型不符合是屬於InputMismatchException吧

"Thrown by a Scanner to indicate that the token retrieved does not match the pattern for the expected type, or that the token is out of range for the expected type"

而NumberFormatException是"Thrown to indicate that the application has attempted to convert a string to one of the numeric types, but that the string does not have the appropriate format."

通常會在字串轉型的時候出現的Exception



收錄日期: 2021-04-13 19:23:00
原文連結 [永久失效]:
https://hk.answers.yahoo.com/question/index?qid=20130323000010KK04839

檢視 Wayback Machine 備份