如何在Java中捕获异常? [英] How to catch an exception in Java?
本文介绍了如何在Java中捕获异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在Java中捕获异常?我有一个程序可以接受整数值的用户输入。现在如果用户输入无效值,它会抛出一个 java.lang.NumberFormatException
。如何捕获该异常?
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
}
这篇关于如何在Java中捕获异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文