I'm trying to use the try-catch to handle user's input exception. Can someone please help me to figure out why it doesn't work? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

I'm trying to use the try-catch to handle user's input exception. Can someone please help me to figure out why it doesn't work?

Scanner usPick = new Scanner(System.in); try { int pick = usPick.nextInt(); //user pick } catch (InputMismatchException e) { System.out.println("Input Error"); } https://code.sololearn.com/cZhc60SBIiEC/?ref=app

21st Aug 2017, 8:47 PM
Ziv
Ziv - avatar
2 Answers
+ 4
That code looks fine to me. You may be having an issue with the scope of the variable. Example fix/ int pick; // enlarging the variables scope try { pick = usPick.nextInt(); } catch(....){ // fail } switch (pick){ case 1: // do stuff with pick break; } Remember if you declare something inside a block, the block is the variables scope. Example/ if (condition){ int x = 15; // X can be accessed in here } // X cannot be accessed out here You can also place the switch case that deals with the variable inside the try block.
21st Aug 2017, 11:00 PM
Rrestoring faith
Rrestoring faith - avatar
+ 2
Thanks a lot for your comment! I think I managed to solve it, you're welcome to check it up :)
22nd Aug 2017, 7:35 AM
Ziv
Ziv - avatar