Reputation: 1930
I have a menu which reads integers for input ,here is the method for the menu:
public int menu(String _menuHeader,String[] _menuItems) throws InvalidInputException {
int choice = 0;
do {
try {
scanner.nextLine();
System.out.println(_menuHeader);
for (int i = 0; i < _menuItems.length; i++) {
System.out.println(" " + (i + 1) + " " + _menuItems[i]);
}
choice = scanner.nextInt();
if (choice <= 0 || choice > _menuItems.length) {
throw new InvalidInputException();
}
} catch (Exception e) {
System.out.println("Enter valid input");
validInput = false;
} catch (InvalidInputException e) {
System.out.println("Please enter a choice between 1 and" + _menuItems.length);
validInput = false;
}
} while (!validInput);
}
Now I want to catch a exception when the input is out of bound of the allowed choices, i.e input 7 for choices 1 and 2,
For this I have tried using InvalidInputException, but this gives a an compile error as 'cannot find symbol InvalidInoutException' although I have imported 'import.java.Throwable/Exception;'
Upvotes: 3
Views: 16543
Reputation: 4069
I didn't look up the import, but the problem is that you catch Exception before InvalidInputException. Java uses the first matching catch to handle an exception, so if you catch a superclass in front of any of its subclasses, the subclass catches will never occur.
Reverse the order of your catches and you'll have better luck.
Edit: OK, I did look it up and Scanner.nextInt() doesn't throw that exception anyway. You probably want java.util.InputMismatchException
, but check for yourself:
http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#nextInt%28%29
PS: This really isn't the best way to handle invalid input, by the way. The Scanner
class has a hasNextInt()
method to detect whether a valid integer is next in the input stream or not. As a rule, it's generally better to avoid throwing and catching exceptions if there's a sensible alternative. The Scanner
hasNext*
methods are specifically designed to give you those sensible alternatives.
Upvotes: 0
Reputation: 8960
There is not such thing as InvalidInputException
in java.lang
. You will have to create your own custom exception, and name it as you wish.
Sorry to say this, but judging from your code you have poor knowledge of how the exception handling works in Java. If this is exception practice, then refactor your code accordingly. If not, don't use exceptions at all. You don't need them in this snippet of code.
Upvotes: 4
Reputation: 706
Do you have a custom exception class defined for your "InvalidInputException"?. If not please go through this post for creating custom exception classes.
How to define custom exception class in Java, the easiest way?
Upvotes: 4