• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • Ron McLeod
  • paul wheaton
  • Jeanne Boyarsky
Sheriffs:
  • Paul Clapham
  • Devaka Cooray
Saloon Keepers:
  • Tim Holloway
  • Roland Mueller
  • Himai Minh
Bartenders:

Looping in exceptions

 
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I'm trying to catch a number from a Scanner. I thought that I could catch the InputMismatchException and re-ask the user to submit another real number.

I use this but if I raise the exception it keeps in an infinite loop:



Thanks!
 
Marshal
Posts: 80748
486
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Because of the exception, the done variable remains false for ever. The Scanner continues to look at the token which wasn't a number, so consume that token with a call to in.next(); inside the catch. No need to do anything with that token.

Then you can enter a new token, and the loop can go round once more.
 
Sheriff
Posts: 22850
132
Eclipse IDE Spring Chrome Java Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You shouldn't use exceptions this way if there are valid checking methods available.
An improved version:
 
reply
    Bookmark Topic Watch Topic
  • New Topic