问题
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);
...
回答1:
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
}
回答2:
you have got try and catch blocks :
try {
Integer.parseInt(yourString);
// do whatever you want
}
//can be a more specific exception aswell like NullPointer or NumberFormatException
catch(Exception e) {
System.out.println("wrong format");
}
回答3:
try {
//codes that thows the exception
} catch(NumberFormatException e) {
e.printTrace();
}
回答4:
Its worth mentioning that it is common for many programmers to catch an exception like so:
try
{
//something
}
catch(Exception e)
{
e.printStackTrace();
}
Even if they know what the problem is or doesnt want to do anything in the catch clause. Its just good programming and can be a pretty useful diagnostic tool.
来源:https://stackoverflow.com/questions/14215694/how-to-catch-an-exception-in-java