我试图覆盖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();
}
}
}
您不需要重写任何内容或创建Throwable
的任何子类。
call 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();
}
}
}
重写不能通过更改现有类来工作。它的工作原理是基于现有类创建一个新类……使用新类