简体   繁体   English

捕获异常后代码无法正常工作

[英]code not working after catching an exception

I'm trying to catch an exception when the value input by the user is not an integer. 当用户输入的值不是整数时,我试图捕获异常。 When a non-integer is input, the exception is caught but it doesn't go back to normal. 输入非整数时,将捕获异常,但不会恢复正常。 What I want it to do is go back to how it starts when the program opens: 我想要它做的是回到程序打开时的启动方式:

private void calculateActionPerformed(java.awt.event.ActionEvent evt) 
{    
    int quantityOfBoxes;
    int width, length, height;
    boolean excep;
    do {
        excep = false;
        try {
            quantityOfBoxes = Integer.parseInt(quantityField.getText());
        } catch (Exception exRef) {
            System.err.println(exRef);
            JOptionPane.showMessageDialog(null,
                "Values must be in integer",
                "Error",
                JOptionPane.WARNING_MESSAGE);
            excep = true;
        }
        quantityField.setText("");
    } while (excep);
}

You should get rid of your while loop. 您应该摆脱while循环。 If an exception is thrown, catch it, but don't continue the loop, since as long as quantityField.getText() doesn't change (actually you change it to "" in the catch block, but that will still throw the same exception), you will keep getting this exception over and over again, and the loop will never terminate. 如果引发了异常,请捕获该异常,但不要继续循环,因为只要quantityField.getText()不变(实际上,您在catch块中将其更改为“”即可,但是仍然会抛出相同的异常quantityField.getText()异常),您将一遍又一遍地获取此异常,并且循环永远不会终止。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM