I\'m just learning Java exception handling and Java in general. I\'ve made a Swing GUI where the user will enter integers into two fields and then click a radio button with an
You should put the try catch block where your Integer.parseInt()
calls.
You'll get exception if you won't check your every event method, so you can do something like that to solve it,
private void aRadioButtonActionPerformed(ActionEvent evt) {
String a = aTextField.getText();
String b = bTextField.getText();
// you may get empty string here so check if the texbox is empty ?
int i=0,j=0;
try{
if(a.length()>0 || b.length()>0){
i = Integer.parseInt(a);
j = Integer.parseInt(b);
}else{
if(a.length()<1 && b.length()>0){
i = Integer.parseInt(a);
}else{
if(b.length()<1 && a.length()>0)
j = Integer.parseInt(b);
}
}
int k = i + j;
}catch(Exception e){
System.out.println("Exception:"+e);
}
cTextField.setText(Integer.toString(k));
}
do the same thing for you -,*,/ radio button listeners too
You need to move your try-catch to the action preformed methods, right now, they are only in when Java is setting up the GUI, when the user preforms the action (actionPreformed) those methods will be called, therefore they need the try-catch, not the setup method.
private void cRadioButtonActionPerformed(ActionEvent evt) {
try {
String a = aTextField.getText();
int i = Integer.parseInt(a);
String b = bTextField.getText();
int j = Integer.parseInt(b);
int k = i * j;
cTextField.setText(Integer.toString(k));
} catch (NumberFormatException e) {
JOptionPane.showMessageDialog(null,
"Error: You must enter an integer");
} catch (ArithmeticException e) {
JOptionPane.showMessageDialog(null,
"Error: You cannot divide by zero");
}
}
Add the try-catch to all the ActionPreformed methods that use this similar code, just make sure each actionPreformed method still has it's own code, just with the try-catch block around it