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