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");
}
}
});
To understand how try-catch block work, I will give an example.
Code block will get executed unless it encounters a statement that tells it to
throw a exception. After throwing the exception, thecatchwill catch the exception and thecatch blockwill get executed.In your case,
The library function
parseDouble()will throw theNumberFormatExceptionso the lines intry blockafter this line, won't get executed.