Throwing and catching exceptions in the same function/method

exceptions

I've written a function that asks a user for input until user enters a positive integer (a natural number). Somebody said I shouldn't throw and catch exceptions in my function and should let the caller of my function handle them.

I wonder what other developers think about this. I'm also probably misusing exceptions in the function. Here's the code in Java:

private static int sideInput()
{
    int side = 0;
    String input;
    Scanner scanner = new Scanner(System.in);

    do {
        System.out.print("Side length: ");
        input = scanner.nextLine();
        try {
            side = Integer.parseInt(input);
            if (side <= 0) {
                // probably a misuse of exceptions
                throw new NumberFormatException();
            }
        }
        catch (NumberFormatException numFormExc) {
            System.out.println("Invalid input. Enter a natural number.");
        }
    } while (side <= 0);

    return side;
}

I'm interested in two things:

  1. Should I let the caller worry about exceptions? The point of the function is that it nags the user until the user enters a natural number. Is the point of the function bad? I'm not talking about UI (user not being able to get out of the loop without proper input), but about looped input with exceptions handled.
  2. Would you say the throw statement (in this case) is a misuse of exceptions? I could easily create a flag for checking validity of the number and output the warning message based on that flag. But that would add more lines to the code and I think it's perfectly readable as it is.

The thing is I often write a separate input function. If user has to input a number multiple times, I create a separate function for input that handles all formatting exceptions and limitations.

Best Answer

The point of an exceptions is that it allows a method to tell that caller that entered a state where it could not continue normally, without forcing you to embed an error code in the return value.

In your case, your method knows exactly what to do when the input is not greater than 0. The only reason you are saving lines here is because you happen to be throwing the same exception you would get if the input was not a number. However, the exception you are throwing does not properly represent why your code does not like the input. If someone else were to come along and see this code, they would have to spend extra time trying to see exactly how things are working.

Related Topic