How to catch an exception in Java? I have a program that accepts user input which is of integer value. Now if the user enters an invalid value, it throws a java.lang.NumberFormatException. How do I catch that exception?
public void actionPerformed(ActionEvent e) {
String str;
int no;
if (e.getSource() == bb) {
str = JOptionPane.showInputDialog("Enter quantity");
no = Integer.parseInt(str);
...
解决方案
try {
int userValue = Integer.parseInt(aString);
} catch (NumberFormatException e) {
//there you go
}
and specifically in your code:
public void actionPerformed(ActionEvent e) {
String str;
int no;
//------------------------------------
try {
//lots of ifs here
} catch (NumberFormatException e) {
//do something with the exception you caught
}
if (e.getSource() == finish) {
if (message.getText().equals("")) {
JOptionPane.showMessageDialog(null, "Please Enter the Input First");
} else {
leftButtons();
}
}
//rest of your code
}