简体   繁体   中英

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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