0

I am pretty new to Java and I have three text fields which are all integers in my Java project. I want to create an if statement that throws an error if the sum of values in text field 1 and 2 are greater than textfield 3. This is what I was able to come up with

if (text3.getText() > (text1.getText()+text2.getText())){
    System.out.println(“Error”)
}

Do I need to put it in a try and catch statement?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197

1 Answers1

0

You can create yourself a new Exception Class:

public class NumberExceededException extends Exception {
    public NumberExceededException(String exceptionMessage){
        super(exceptionMessage);
    }
}

Then use it with:

If (text3.getText() > (text1.getText()+text2.getText())) {
    throw new NumberExceededException("You have exceeded my expectations");
}

This will throw a new bubbling exception which can be caught by a try catch higher up.

Just to note that this is not exclusive to Netbeans it is a Java function, Netbeans is an IDE and only outputs whatever the JVM tells it to output.

TravisF
  • 459
  • 6
  • 13
  • I got an error when I tried this: "public class NumberExceededException extends Exception { public NumberExceededException(String exceptionMessage){ super(exceptionMessage); } } try{ If (Container_Num.getText() > (size20.getText()+size40.getText())){ throw new NumberExceededException("You have exceeded it"); } catch (NumberExceededException ex) { java.util.logging.Logger.getLogger(Integral_F.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } }" – Kwadwo Sarpong Kyei Aug 03 '21 at 04:14
  • If you are going to use a nested class it has to be inside the java class but not inside a method. I would recommend however making the exception its own java file then importing it and using it that way, it's better than nesting classes. – TravisF Aug 03 '21 at 04:24