-1
import javax.swing.*;

class gui {

    public static void main(String[] args) {

        //Scanner obj = new Scanner(System.in);
        String s = " ";
        s = JOptionPane.showInputDialog(null, "enter first value");
        String ab = s;
        int value1 = Integer.parseInt(ab);

        String s2 = " ";
        s2 = JOptionPane.showInputDialog(null, "enter second value");
        String cd = s2;
        int value2 = Integer.parseInt(cd);

        JOptionPane.showMessageDialog(null, " the result " + (value1 + value2));

    }
}
guido
  • 18,864
  • 6
  • 70
  • 95

1 Answers1

1

Integer.parseInt() can throw an NumberFormatException, i.e. Integer.parseInt("abc"). Whilst you don't have to catch it (it's an unchecked exception), you should make sure your code can handle such input. For example, if you do handle it with a catch:

try {
   Integer.parseInt(ab);
} catch (NumberFormatException e) {
   // Handle exception i.e. display error
}

Please check out the documentation on Integer.parseInt here.

Also please see this related question for useful information on unchecked exceptions and why in this case (working with UI) you should probably catch it.

Community
  • 1
  • 1
xlm
  • 6,854
  • 14
  • 53
  • 55
  • 1
    `NumberFormatException` is an unchecked exception (extending from `RuntimeException`), it doesn't "have" to be caught – MadProgrammer Mar 11 '15 at 04:35
  • @MadProgrammer, ah I didn't realise that. Thanks! +1 I'll edit the answer appropriately. – xlm Mar 11 '15 at 04:39