JAVA - Try/Catch遇到困难

Kid*_*mer 2 java try-catch

我正在为课堂写一个直接的机场航站楼风格的课程.我超出了作业范围并"尝试"使用Try/Catch块......

然而Java现在就是那个人.

问题是当有人在下面的代码中输入一个非字母时它没有捕获然后返回它捕获的try块...

为什么?

编辑 - 此外,containsOnlyLetters方法有效,除非有人认为可能是错误?

System.out.println("\nGood News! That seat is available");

try
{//try
    System.out.print("Enter your first name: ");
    temp = input.nextLine();
        if (containsOnlyLetters(temp))
            firstName = temp;
        else
            throw new Exception("First name must contain"
                    + " only letters");

    System.out.print("Enter your last name: ");
    temp = input.nextLine();
        if (containsOnlyLetters(temp))
            lastName = temp;
        else
            throw new Exception("Last name must contain"
                    + " only letters");
}//end try

catch(Exception e)
{//catch
    System.out.println(e.getMessage());
    System.out.println("\nPlease try again... ");
}//end catch

passengers[clients] = new clientInfo
            (firstName, lastName, clients, request, i);
bookSeat(i);
done = true;
Run Code Online (Sandbox Code Playgroud)

Mic*_*rdt 10

你似乎误解了try/catch的目的和机制.

不是用于一般流控制,更具体地说,意思不是重复尝试块直到它完成而没有异常.相反,该块只运行一次,重点是只有在抛出匹配的异常时catch块才会执行.

你应该为你的代码使用while循环和if子句,而不是try/catch.