我試圖覆蓋Java中的NumberFormatException類中的getMessage()方法,該方法是未經檢查的異常。出於某種原因,我無法覆蓋它。我知道這一定很簡單,但不明白我可能會錯過什麼。有人可以幫忙嗎?這裏是我的代碼:從Java中未經檢查的Exception類中覆蓋方法
public class NumberFormatSample extends Throwable{
private static void getNumbers(Scanner sc) {
System.out.println("Enter any two integers between 0-9 : ");
int a = sc.nextInt();
int b = sc.nextInt();
if(a < 0 || a > 9 || b < 0 || b > 9)
throw new NumberFormatException();
}
@Override
public String getMessage() {
return "One of the input numbers was not within the specified range!";
}
public static void main(String[] args) {
try {
getNumbers(new Scanner(System.in));
}
catch(NumberFormatException ex) {
ex.getMessage();
}
}
}
實際上規範提到我應該只拋出一個NumberFormatException對象。 – Setafire 2013-05-01 01:10:11
@Setafire:查看我的編輯。 – jlordo 2013-05-01 01:12:48
是的,我剛剛得到了。正在編輯原文,但您已經先編輯了您的文章。 – Setafire 2013-05-01 01:18:01