0

I'm looking for an exception on how to catch an invalid String that is user input. I have the following code for a exception on an integer input:

            try {
            price = Integer.parseInt(priceField.getText());
            }
            catch (NumberFormatException exception) { 
            System.out.println("price error");
            priceField.setText("");
            break;

But I'm not aware of a specific exception for strings, the input is a simple JTextBox so the only incorrect input I can think of is if the user enters nothing into the box, which is what I'm looking to catch.

4 Answers 4

6
if (textField.getText().isEmpty())

is all you need.

Or maybe

if (textField.getText().trim().isEmpty())

if you also want to test for blank inputs, containing only white spaces/tabs.

You generally don't use exceptions to test values. Testing if a string represents an integer is an exception to the rule, because there is no available isInt() method in String.

Sign up to request clarification or add additional context in comments.

Comments

0

You can do like

if (priceField.getText().isEmpty()) 
  throw new Exception("priceField is not entered.");

Comments

0

You could check if priceField contains a string by using this:

JTextField priceField;
int price;
try {
 // Check whether priceField.getText()'s length equals 0
 if(priceField.getText().getLength()==0) {
  throw new Exception();
 }
 // If not, check if it is a number and if so set price
 price = Integer.parseInt(priceField.getText());
} catch(Exception e) {
 // Either priceField's value's length equals 0 or
 // priceField's value is not a number

 // Output error, reset priceField and break the code
 System.err.println("Price error, is the field a number and not empty?");
 priceField.setText("");
 break;
}

When the if-statement is true (If the length of priceField.getText() is 0) an exception gets thrown, which will trigger the catch-block, give an error, reset priceField and break the code.

If the if-statement is false though (If the length of priceField.getText() is greater or lower than 0) it will check if priceField.getText() is a number and if so it sets price to that value. If it not a number, a NumberFormatException gets thrown, which will trigger the catch-block etc.

Let me know if it works.

Happy coding :) -Charlie

Comments

0

if you want your exception to be thrown during the normal operation of the Java Virtual Machine, then you can use this

if (priceField.getText().isEmpty()) 
    throw new RunTimeException("priceField is not entered.");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.