File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
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 EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Looping in exceptions" Watch "Looping in exceptions" New topic
Author

Looping in exceptions

Carlos Obregon
Greenhorn

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:



Thanks!
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 36453
    
  15
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.
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19541
    
  16

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


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