简体   繁体   中英

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
}

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;
    }
}

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;
  }
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM