java - switch block try/catch exception -
this question has answer here:
i have switch statement 5 integer options , default message. trying work if other choice numbers chosen, "invalid input" message show up. works numbers, if else entered, following exception:
exception in thread "main" java.util.inputmismatchexception
i tried add try/catch statement, doesn't seem working; keep getting 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!"); } } }
if program terminates java.util.inputmismatchexception follows that exception not thrown within try block presented. inasmuch exception associated entering input in unexpected form, , inasmuch attempt convert input number evidently has been performed in method menu(), before entering try block, seems reasonable conclude exception thrown method menu(). stack trace accompanying exception have told directly, , more precisely can presented.
based on nature of task , type of exception received, speculate using scanner read user input, , invoking scanner.nextint(). method throw exception of type specified if invoked when next token cannot interpreted java int.
only can decide how best deal that, 1 possibility move invocation of menu() method inside try block:
// ... while (menuitem != 0) { try { menuitem = menu(); switch (menuitem) { // ...
Comments
Post a Comment