Continue executing loop after catching an exception in try/catch

前端 未结 3 2018
太阳男子
太阳男子 2021-01-17 23:54

Once an exception is caught in this code, the menuSystem method is run, but once I go to input a number the programme closes and the \"Build is successful\" mes

相关标签:
3条回答
  • 2021-01-18 00:41

    put your try/catch inside your while loop:

        while (option != 0) {
            final Scanner keyb = new Scanner(System.in);
            System.out.println("");
            try {
                switch (option) {
    
                }
            } catch (Exception InputMismachException) {
                System.out.println("\nPlease Enter a Valid Number\n");
                option = menuSystem();
            }
        }
    
    0 讨论(0)
  • 2021-01-18 00:48

    Another way you can do it:

       List<File> directories;
       ...
       for ( File f : directories ) {
            try {
                processFolder(f);
            } catch( Exception e ) {
                SimpleLog.write(e);
            }
        }
    
    0 讨论(0)
  • 2021-01-18 00:53

    Put the try and catch within the while loop. If the code is using nextInt() then you need to skip the invalid input as it will not be consumed in the event of a mismatch.

    It would be possible to avoid the exception handling for InputMismatchException by using the hasNextInt() methods of Scanner until a valid input is entered before attempting to consume it:

    while (!kb.hasNextInt()) kb.next();
    
    0 讨论(0)
提交回复
热议问题