Home > database >  How to handle java exception InputMismatchException along with custom exceptions?
How to handle java exception InputMismatchException along with custom exceptions?

Time:10-04

I'm making a simple program that is a guessing game all you need to do is guess the random number. As long as your not getting the correct answer it will keep asking for input.

I created two exceptions which is thrown if the input value is high or low which works.

I also needed to use another exception which is InputMismatchException but when its used its giving me an infinite loop. Instead of asking the user for input it just skips directly to the InputMismatchException. How do I get it to work with my custom exceptions?

import java.util.*;

public class Main {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);

        final int min = 1, max = 50;
        final int random = (int) Math.floor(Math.random() * (max - min   1)   min);

        boolean status = false;
        int count = 0;

        while (status != true) {

            try {

                System.out.println("Guess a number from 1 to 50: ");
                int answer = scan.nextInt();

                if (answer < random) {

                    throw new InputTooLowException("");

                } else if (answer > random) {

                    throw new InputTooHighException("");

                } else if (answer == random) {

                    System.out.println("\n"   "Congratulations! You got it in "   count   " attempt/s");
                    status = true;
                }

            } catch (InputTooLowException e) {
                System.out.println("Too low. Try again.");
                status = false;
                count = count   1;

            } catch (InputTooHighException e) {
                System.out.println("Too high. Try again.");
                status = false;
                count = count   1;

            } catch (InputMismatchException e) {
                System.out.println("Invalid Input");
                status = false;
            }

        }

    }
}

CodePudding user response:

This program works for me. Again, I want to highlight that this is a bad/non-idiomatic use of Exceptions.

I highly recommend Joshua Blochs famous Book "Effective Java". Chapter 10, Item 69 is about this: "Use exceptions only for exceptional conditions".

The Carnegie Mellon University Software Engineering Institute also has this in their coding guidelines.

Now regarding the infinite loop: I didn't realize that InvalidInputException is not one of your custom Exceptions, but from java.util and thrown by scan.nextInt.

The documentation of Scanner says:

When a scanner throws an InputMismatchException, the scanner will not pass the token that caused the exception, so that it may be retrieved or skipped via some other method.

That means, if you type in text, not a number, Scanner will let you know, but not simply throw away the input. You have to handle it yourself. E.g., by calling next. I have added a check hasNext here. A user could press Ctrl d which means something like "End of File" (EOF). This closes the input stream. My check prevents an error here, but your call to nextInt may then throw a NoSuchElementException. This should be handled in real code, but I doubt your professor will notice.

import java.util.*;

public class Main {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);

        final int min = 1, max = 50;
        final int random = (int) Math.floor(Math.random() * (max - min   1)   min);

        boolean status = false;
        int count = 0;

        while (status != true) {

            try {

                System.out.println("Guess a number from 1 to 50: ");
                int answer = scan.nextInt();

                // Note that this is a _terrible_ use of Exceptions
                // and _bad practice_.
                if (answer < random) {

                    throw new InputTooLowException("");

                } else if (answer > random) {

                    throw new InputTooHighException("");

                } else if (answer == random) {

                    System.out.println("\n"   "Congratulations! You got it in "   count   " attempt/s");
                    status = true;
                }

            } catch (InputTooLowException e) {
                System.out.println("Too low. Try again.");
                count = count   1;

            } catch (InputTooHighException e) {
                System.out.println("Too high. Try again.");
                count = count   1;
            } catch (InputMismatchException e) {
                System.out.println("Invalid Input");

                // Check if there actually is an invalid token
                if (scan.hasNext()) {
                    // Discard invalid token
                    scan.next();
                }
            }

        }

    }

    // Defining Exceptions here, but could do it in their own files.
    private static class InputTooHighException extends Exception {
                public InputTooHighException(String msg) { super(msg); }
    }

    private static class InputTooLowException extends Exception {
                public InputTooLowException(String msg) { super(msg); }
    }
}
  • Related