【问题标题】:Catch block in Java code gets executed even when the try block satisfies the mentioned condition?即使 try 块满足上述条件,Java 代码中的 Catch 块也会被执行?
【发布时间】:2021-07-14 11:50:04
【问题描述】:

我是 Java 新手,我尝试在我的 Java 代码中使用异常来提醒用户,如果他/她在文本字段中键入负数或非数字值。但是,当我输入一个个位数的正数时,catch 块会被执行。

    //textfield to enter the amount of Rs.
    txt_rupees = new JTextField();
    
    //KeyListener to check if the content entered in the text field is a number or not.
    txt_rupees.addKeyListener(new KeyAdapter() {
        
        public void keyPressed(KeyEvent e) {
            
            try {
                //convert the user input in the textfield from string to double
                double check = Double.parseDouble(txt_rupees.getText());
                
                //checking if the number entered by the user is positive or not.
                if (check > 0) {
                lb_check1.setText(" ");             
                }
                
                else {
                    lb_check1.setText("Please enter a valid number");
                }
            }       
            catch (NumberFormatException ne){
                
                //If the user enters a non-numerical character then this message should be displayed by the label.
                lb_check1.setText("ALERT: Please enter a valid float or int value in the textfield");
            }
        }           
    });

【问题讨论】:

  • 只有当 NumberFormatException 被扔进 de try 块时才会执行你的 catch 块。很可能你插入了数字,但是解析函数会为任何事情抛出错误(也许它在 keyPressed 事件上只是空的)。跟踪ne 错误以便更准确地确定错误

标签: java exception try-catch catch-block


【解决方案1】:

为了理解 try-catch 块的工作原理,我举个例子。

class InsufficientMoneyException extends Exception{
    InsufficientMoneyException(int money){
        System.out.println("You only have $"+money);
    }
}

class A throws InsufficientMoneyException{
 try{
  int money = 100;
  if(money<1000) throw new InsufficientMoneyException(money);
  System.out.println("I am NOT being executed!");

 } catch (InsufficientMoneyException e){System.out.println("I am being executed!");}
}

除非遇到将其告知throw a exception 的语句,否则代码块将被执行。抛出异常后,catch 将捕获异常,catch block 将被执行。

在你的情况下,

                double check = Double.parseDouble(txt_rupees.getText());  

库函数parseDouble() 将抛出NumberFormatException,因此该行之后的try block 中的行将不会被执行。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-08-28
    • 2017-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-02
    • 1970-01-01
    • 2021-08-07
    相关资源
    最近更新 更多