I am trying to override the getMessage() method in the NumberFormatException class in Java, which is an unchecked Exception. For some reason, I am unable to override it. I know it must be something really simple, but can't understand what I could be missing. Could someone please help? Here is my code:
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();
}
}
}
EDIT (after your comment).
Seems you are looking for:
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());
}
}
}