Infinite Loop in Exception Handling

Asked

Viewed 123 times

0

I’m trying to make a try to ask for the option number for the user, but I want to do this until he type an integer number, I did a Try/catch, but when I run it and digit a string it keeps sending an error message several times, and I can’t identify the error;

public class CaniveteSuico {

    static Scanner in = new Scanner (System.in);

    public Integer Menu() {
        int  opcao=0;
        int checar=0;
        do {
            checar=0;

            System.out.println("\n  ==================================");
            System.out.println("  |     1 - Gestão de Produtos      |");
            System.out.println("  |     2 - Gestão de Vendas        |");
            System.out.println("  |     3 - Gestão de Pessoas       |");
            System.out.println("  |     0 - Sair                    |");
            System.out.println("  ===================================\n");
            System.out.print(" Opção -> ");

            try {
                opcao = in.nextInt();  
                System.out.print("\n");
                checar =1;
            } catch(Exception e) {
                System.err.println("Você digitou um caractere inválido! Tente novamente ");
            }
        } while(checar==0);

    return opcao;
}

}

1 answer

0


It turns out that there is an exception of the type InputMismatchException causes the content not to be consumed. So you are trying to read an integer and the user puts a text as "teste" an exception is made and the text "teste" continues there. This means that when you do it again nextInt to read again, again catch the same exception. The solution is to clear what was forcing a reading in String for example, using nextLine:

try {
    opcao = in.nextInt();  
    System.out.print("\n");
    checar =1;
} catch(Exception e) {
    in.nextLine(); //"limpa" o que ficou por ler que não era inteiro
    System.err.println("Você digitou um caractere inválido! Tente novamente ");
}

It is however important to mention that you should always capture only the exception you are interested in and not all as you are using Exception, because in some cases you might catch other exceptions that you wouldn’t expect and give the same treatment without realizing it. Then I could rewrite by just capturing InputMismatchException:

try {
    opcao = in.nextInt();  
    System.out.print("\n");
    checar =1;
} catch(InputMismatchException« e) {
//            ^--- captura apenas o tipo que interessa
    in.nextLine();
    System.err.println("Você digitou um caractere inválido! Tente novamente ");
}
  • Thank you very much, solved my problem! Hug!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.