This week's book giveaway is in the Java 8 forum.
We're giving away four copies of Java 8 in Action and have Raoul-Gabriel Urma, Mario Fusco, and Alan Mycroft on-line!
See this thread for details.
The moose likes Java in General and the fly likes Looping in exceptions Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java 8 in Action this week in the Java 8 forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Looping in exceptions" Watch "Looping in exceptions" New topic

Looping in exceptions

Carlos Obregon

Joined: May 26, 2009
Posts: 18
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:

Campbell Ritchie

Joined: Oct 13, 2005
Posts: 36575
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; 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.
Rob Spoor

Joined: Oct 27, 2005
Posts: 19556

You shouldn't use exceptions this way if there are valid checking methods available.
An improved version:

How To Ask Questions How To Answer Questions
I agree. Here's the link:
subject: Looping in exceptions
Similar Threads
Problem with PrintWriter and another Problem with Inputhandling
How to reiterate a do while loop after an exception is caught, run time error handling issue
try...catch blocks giving <identifier> expected error
Initial variables before a try\catch block
Unexpected Recursion