[英]Override a method from an unchecked Exception class in Java
我試圖覆蓋Java中NumberFormatException類中的getMessage()方法,這是未經檢查的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();
}
}
}
您不需要重寫任何內容或創建Throwable
任何子類。
只需調用throw new NumberFormatException(message)
。
編輯 (在您的評論后)。
似乎您在尋找:
public class NumberFormatSample {
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("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) {
System.err.println(ex.getMessage());
}
}
}
正如其他答案所指出的那樣,您實際上要執行的操作根本不需要覆蓋。
但是,如果確實需要重寫NumberFormatException
的方法,則必須:
extend
這個類,不Throwable
,並 NumberFormatException
。 例如:
// (Note: this is not a solution - it is an illustration!)
public class MyNumberFormatException extends NumberFormatException {
private static void getNumbers(Scanner sc) {
...
// Note: instantiate "my" class, not the standard one. If you new
// the standard one, you will get the standard 'getMessage()' behaviour.
throw new MyNumberFormatException();
}
@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));
}
// Note: we can still catch NumberFormatException, because our
// custom exception is a subclass of NumberFormatException.
catch (NumberFormatException ex) {
ex.getMessage();
}
}
}
通過更改現有類無法進行覆蓋。 它通過基於現有的類創建一個新類並使用新類來工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.