带有NumberFormatException的捕获块被忽略了吗?

时间:2018-06-25 14:18:32

标签: java input try-catch numberformatexception

当用户输入无效或什么都不输入时,我正在尝试发送错误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);
    }
}
}   

很抱歉,该代码可能不符合代码约定,但我删去了所有不重要的部分,因此,我可能将代码改成了“丑陋的”。

1 个答案:

答案 0 :(得分:2)

将try catch块放入动作侦听器中。动作侦听器是一个不同的类,因此您当前的try catch块将不会捕获其中的异常。