Catch block in Java code gets executed even when the try block satisfies the mentioned condition?

536 views Asked by At

I am new to Java and I tried to use exceptions in my Java code to give the user an alert if in case he/she types a negative number or a non-numerical value in the text field. But still, when I enter a single-digit positive number, the catch blocks get executed.

    //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");
            }
        }           
    });
1

There are 1 answers

0
Daoist Paul On

To understand how try-catch block work, I will give an example.

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!");}
}

Code block will get executed unless it encounters a statement that tells it to throw a exception. After throwing the exception, the catch will catch the exception and the catch block will get executed.

In your case,

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

The library function parseDouble() will throw the NumberFormatException so the lines in try block after this line, won't get executed.