Rassisland February 2016

switch block try/catch exception

I have a switch statement with 5 integer options and a default message. I am trying to get it to work so that if anything other than the choice numbers is chosen, an "Invalid Input" message will show up. It currently works for numbers, but if anything else is entered, I get the following exception:

Exception in thread "main" java.util.InputMismatchException

I tried to add a try/catch statement, but it doesn't seem to be working; I keep getting the same error message.

public static void main(String[] args) throws IOException {
    int menuItem = -1;
    while (menuItem != 0) {
        menuItem = menu();
        try {
            switch (menuItem) {
                case 1:
                    showTaskList();
                    break;
                case 2:
                    addTask();
                    break;
                case 3:
                    sortList();
                    break;
                case 4:
                    deleteTasks();
                    break;
                case 0:
                    break;
                default:
                    System.out.println("Invalid Input");
                    break;
            }
        }
        catch (java.util.InputMismatchException err) {
            System.out.println("\nINVALID INPUT!");
        }
    }
}

Answers


John Bollinger February 2016

If your program terminates with a java.util.InputMismatchException then it follows that that exception was not thrown from within the try block you presented. Inasmuch as that exception is associated with entering input in an unexpected form, and inasmuch as an attempt to convert the input to a number evidently has already been performed in method menu(), before entering the try block, it seems reasonable to conclude that the exception is thrown from method menu(). The stack trace accompanying the exception would have told you this directly, and more precisely than I can from what you presented.

Based on the nature of the task and the type of exception you received, I speculate that you are using a Scanner to read user input, and specifically that you are invoking Scanner.nextInt(). This method will throw an exception of the type you specified if invoked when the next token cannot be interpreted as a Java int.

Only you can decide how best to deal with that, but one possibility is to move invocation of the menu() method inside your try block:

    // ...
    while (menuItem != 0) {
        try {
            menuItem = menu();
            switch (menuItem) {
            // ...

Post Status

Asked in February 2016
Viewed 3,145 times
Voted 13
Answered 1 times

Search




Leave an answer