3

I am trying to loop a try block every time an exception is thrown.

An example might be when the program prompts for a double and the user enters a string, so, a NumberFormatException is thrown. So the program will request the user to re-enter.

Here's what I am doing currently. Is this the proper way to do so or is there better way?

// infinite loop
for (;;)
{     
    try 
    {
        //do something
        break; // if an exception is not thrown. it breaks the loop.
    }
    catch (Exception e)
    {
        //display the stack trace.
    }

    // restarts the for loop
}
skolima
  • 31,963
  • 27
  • 115
  • 151
Nyx
  • 1,273
  • 6
  • 19
  • 32
  • Heh, I dealt with a similar problem in my [blog](http://blog.engineering.vayana.in/case-study-in-dsl-development-with-scala-part-1/) recently, albeit in a different language. (see bullet 4) – missingfaktor Feb 03 '12 at 06:02
  • Ah, ok. This snippet is fully functional. I just want to make sure my method is a generally accepted way of doing it. – Nyx Feb 03 '12 at 06:04
  • 1
    Hi Marv, you can take a look at my example code for you. If you are gonna collect input many times, you can display input constraints once at the beginning or warning the user every time. It is a good alternative to catching exceptions. With this technique you are able to force users obey your input constraints as well, for instance it can be used for controlling a text field that is desired to accept just a particular string/numerical pattern. – Juvanis Feb 03 '12 at 06:24

3 Answers3

3

Instead of throwing exceptions according to the input, keep your restrictions on the user input by getting use of the regular expressions. Java regular expressions will help you at this point.

import java.util.Scanner;
import java.util.regex.Pattern;

public class Sample
{
    private final static Pattern DIGITS = Pattern.compile( "\\d*" );

    public static void main ( String [] args )
    {
        Scanner scanner = new Scanner( System.in );
        while ( true )
        {
            String input = scanner.nextLine();
            if ( evalInput( input ) )
                process( input );
            else
                System.out.println("Input constraints: it must be just numerical.");
        }
    }

    public static void process ( String str )
    {
        // Whatever you wanna do with the accepted input.
    }

    public static boolean evalInput ( String str )
    {
        if ( str != null && DIGITS.matcher( str ).matches() )
            return true;
        return false;
    }
}
Juvanis
  • 25,802
  • 5
  • 69
  • 87
3

I'd do it just like you did, perhaps adding a prompt to re-enter.

while(true) {
  try {
    String s = read.nextLine();
    i = Integer.parseInt(s);
    break;
  } catch(NumberFormatException) {
    System.out.println("Please try again.");
    continue;
  }
}
missingfaktor
  • 90,905
  • 62
  • 285
  • 365
0

In this case I'd rather put the whole try-block inside the loop. I think it's easier to read than breaking out of try:

while (true) {
    try {
        ...
    } catch (...) {
        ...
    }
}

Also, I fin it clearer to write while (true) for an infinite loop, and wouldn't normaly use exceptions to handle user input.

Axel
  • 13,939
  • 5
  • 50
  • 79