当用户输入无效或什么都不输入时,我尝试发送错误 JOptionPane。我正在尝试使用 try/catch block 和 NumberFormatException 来执行此操作,但在我看来,该 block 被忽略,但这是不可能的。
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);
}
}
}
很抱歉,代码可能不符合代码约定,但我删除了所有不重要的部分,因此,我可能使代码变得“更丑”。
最佳答案
将 try catch block 放入操作监听器中。操作监听器是一个不同的类,因此当前的 try catch block 不会捕获其中的异常。
关于java - 带有 NumberFormatException 的 Catch block 被忽略?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51025677/