• Post Reply Bookmark Topic Watch Topic
  • New Topic

What is the right try/catch for an InputMismatchException?  RSS feed

 
Ranch Hand
Posts: 60
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I know this exception is not correct because I get that long java.util.InputMismatchException error. The program still allows the user to re-enter but I obviously don't want the long error. What's the actual way to do it?

 
Rancher
Posts: 989
9
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
So remove the e.printStackTrace();
Also, if you want to ignore only the InputMismatchException then that should be the one you catch and ignore not the blanket Exception you are catching.
 
Marshal
Posts: 56608
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You never need to catch an InputMismatchException because, as Rob Spoor points out, you can always avoid it. There should be no need to check hasNext() if you use System.in because you should never close a reader or scanner pointing to System.in.

Never use == true or == false, which are poor style and very error‑prone. It's while (flag)... or while (!flag)...
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!