【问题标题】:Catch-block with NumberFormatException is being ignored?NumberFormatException 的捕获块被忽略了吗?
【发布时间】: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


【解决方案1】:

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

【讨论】:

  • 实际上它本质上是另一个(如果它是一个方法,异常就会被捕获) - 解决方案将try-catch移到lambda内部
  • 这样看:catch 块只保护执行button.addActionListener。不执行圆括号内的内容,它只是一个参数(ActionListener)。此时,监听器只是数据,并没有被执行。
猜你喜欢
  • 1970-01-01
  • 2020-07-07
  • 2020-04-18
  • 1970-01-01
  • 1970-01-01
  • 2011-12-18
  • 2010-12-17
  • 2019-03-07
  • 2020-06-18
相关资源
最近更新 更多