0

我试图覆盖 Java 中 NumberFormatException 类中的 getMessage() 方法,这是一个未经检查的异常。出于某种原因,我无法覆盖它。我知道这一定很简单,但不明白我可能会错过什么。有人可以帮忙吗?这是我的代码:

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

}

4

3 回答 3

3

您不需要覆盖任何内容或创建任何Throwable.

只要打电话throw new NumberFormatException(message)

于 2013-05-01T01:10:36.710 回答
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());
        }
    }
}
于 2013-05-01T01:08:24.533 回答
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();
        }
    }
}

通过更改现有类无法覆盖。它的工作原理是在现有类的基础上创建一个新类……并使用新类。

于 2013-05-01T01:22:05.593 回答