【发布时间】:2018-06-25 14:18:31
【问题描述】:
当用户输入无效或根本没有输入时,我试图发送错误 JOptionPane。我正在尝试使用 try/catch 块和 NumberFormatException 来执行此操作,但在我看来,该块被忽略了,但这是不可能的。
import javax.swing.*;
import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionListener;
import java.lang.NumberFormatException;
public abstract class Input extends JFrame implements ActionListener {
public static void main(String[] args) throws NumberFormatException {
//implementation of the GUI with JTexFields etc.
try {
button.addActionListener(e -> {
Label.setText(" ");
int Num1 = 5;
int Num2 = Integer.valueOf(Field1.getText());
if (Num1 <= 0) {
//something;
}
//calculate with input
});
}
catch (NumberFormatException e) {
JOptionPane.showMessageDialog(null,
"Please watch out for your input.",
"Input error",
JOptionPane.ERROR_MESSAGE);
}
}
}
很抱歉,代码可能不符合代码约定,但我删除了所有不重要的部分,因此,我可能使代码“更丑”。
【问题讨论】:
-
尝试调试一下。
-
NumberFormatException在 lambda 表达式中被抛出,可能不会被重新抛出。
标签: java input try-catch numberformatexception