Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looping Try Statement

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
}
like image 222
Nyx Avatar asked Mar 14 '26 23:03

Nyx


2 Answers

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;
    }
}
like image 125
Juvanis Avatar answered Mar 17 '26 11:03

Juvanis


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;
  }
}
like image 41
missingfaktor Avatar answered Mar 17 '26 13:03

missingfaktor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!