0

我試圖覆蓋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(); 
    } 
} 

}

回答

1

編輯(您的評論之後)。

好像你正在尋找:

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()); 
     } 
    } 
} 
+0

實際上規範提到我應該只拋出一個NumberFormatException對象。 – Setafire 2013-05-01 01:10:11

+0

@Setafire:查看我的編輯。 – jlordo 2013-05-01 01:12:48

+0

是的,我剛剛得到了。正在編輯原文,但您已經先編輯了您的文章。 – Setafire 2013-05-01 01:18:01

3

你並不需要覆蓋任何東西,或創建Throwable任何子類。請致電throw new NumberFormatException(message)

+0

謝謝你做到了。 – Setafire 2013-05-01 01:19:29

1

正如其他答案指出的那樣,你實際上試圖做的事情根本不需要重寫。

但是,如果你真的需要在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(); 
     } 
    } 
} 

重寫不改變現有類工作。它通過創建基於現有類的新類以及使用新類來實現。

+0

感謝您的好解釋。 – Setafire 2013-05-01 01:24:22