try-catch语句在捕获异常时不返回try块

时间:2014-03-16 17:55:37

标签: java try-catch

我有一个写的方法。此方法只扫描用户输入的整数输入。如果用户输入字符值,它将抛出输入不匹配异常,这在我的Try-Catch语句中处理。问题是,如果用户输入任何不是数字的东西,然后抛出异常,我需要循环回来再次询问用户输入。据我所知,如果发现错误,Try catch语句会自动循环回Try块。这不正确吗?请指教。

这是我的方法(非常简单):

public static int getMask() {
        //Prompt user to enter integer mask
        Scanner keyboard = new Scanner(System.in);
        int output = 0;
        try{
            System.out.print("Enter the encryption mask: ");
            output = keyboard.nextInt();
        }
        catch(Exception e){
            System.out.println("Please enter a number, mask must be numeric");
        }
        return output;
    }//end of getMask method

以下是该方法在我的程序中的实现方式:

//get integer mask from user input
        int mask = getMask();
        System.out.println("TEMP mask Value is: " + mask);

/ * ** * ** * ** * ** * ** * ** * ** * ** * ** * ** * ** * * / 这是我更新的代码。它创造了一个我无法逃脱的无限循环。我不明白为什么我这么苦苦挣扎。请帮忙。

public static int getMask() {
    //Prompt user to enter integer mask
    Scanner keyboard = new Scanner(System.in);
    int output = 0;
    boolean validInput = true;

    do{
    try {
        System.out.print("Enter the encryption mask: ");
        output = keyboard.nextInt();
        validInput = true;
    }
    catch(InputMismatchException e){
        System.out.println("Please enter a number, mask must be numeric");
        validInput = false;
        }
    }while(!(validInput));

    return output;

/ * ** * ** * ** * ** * ** * **** / FINAL_ANSWER 我终于得到了它。我想我只需要更多地学习布尔逻辑。有时它让我头晕。用整数测试实现循环工作正常。我想我自己的用户错误。这是我的最终代码正常工作,更好的异常处理。如果你有任何批评,请在评论中告诉我。

//get integer mask from user input
        int repeat = 1;
        int mask = 0;
        do{
            try{

        mask = getMask();
        repeat = 1;
            }
            catch(InputMismatchException e){
                repeat = 0;
            }
        }while(repeat==0);

3 个答案:

答案 0 :(得分:2)

  

据我所知,如果发现错误,Try catch语句会自动循环回Try块。这不正确吗?

不,这不正确,我很好奇你是如何达成这种理解的。

您有几个选择。例如(这不会按原样工作,但我们首先讨论错误处理,然后在下面阅读):

// Code for illustrative purposes but see comments on nextInt() below; this
// is not a working example as-is.
int output = 0;
while (true) {
    try{
        System.out.print("Enter the encryption mask: ");
        output = keyboard.nextInt();
        break;
    }
    catch(Exception e){
        System.out.println("Please enter a number, mask must be numeric");
    }
}

其中;你选择的选项通常取决于你喜欢的口味(例如fge's answer是相同的想法,但略有不同),但在大多数情况下直接反映你想要做的事情:“继续询问,直到用户输入有效号码。“

另请注意,与fge一样,您通常应该抓住您准备处理的最严重的异常。 nextInt()引发了一些不同的例外,但您的兴趣特别在于InputMismatchException。您不准备处理,例如,IllegalStateException - 更不用说如果抛出意外异常会使调试/测试变得困难,但是您的程序假装它们只与无效输入相关(因此从不通知您发生了不同的问题。)

现在,那里说Scanner.nextInt()还有另一个问题,如果它不能被解析为整数,那么令牌就会留在流上。如果您不从流中取出该令牌,这将使您陷入循环。为此,您实际上想要使用next()nextLine(),以便无论如何总是使用令牌;然后你可以用Integer.parseInt()解析,例如:

int output = 0;
while (true) {
    try{
        System.out.print("Enter the encryption mask: ");
        String response = keyboard.next(); // or nextLine(), depending on requirements
        output = Integer.parseInt(response);
        break;
    }
    catch(NumberFormatException e){ // <- note specific exception type
        System.out.println("Please enter a number, mask must be numeric");
    }
}

请注意,这仍然直接反映了您要执行的操作:“在用户输入有效数字之前不断询问,但无论输入什么,都会消耗输入。”

答案 1 :(得分:1)

  

据我所知,如果发现错误,Try catch语句会自动循环回Try块。这不正确吗?

确实不正确。 try块只会执行一次。

您可以使用它来“解决”它(尽管JasonC's answer更加稳固 - 请继续使用):

boolean validInput = false;

while (!validInput) {
    try {
        System.out.print("Enter the encryption mask: ");
        output = keyboard.nextInt();
        validInput = true;
    }
    catch(Exception e) {
        keyboard.nextLine(); // swallow token!
        System.out.println("Please enter a number, mask must be numeric");
    }
}
return output;

进一步说明:您不应该捕获Exception,而应该捕获更具体的异常类。

答案 2 :(得分:0)

如评论中所述,try-catch -blocks不会循环播放。如果要循环,请使用forwhile