Failing constructor intentionally to stop the instantiation of an object

I had a function outside a class that performs some checks before making the object from the class. If the incoming parameter was faulty, it would return null instead of the object.

Then it occured to me that it would be nicer to have this function as a 2nd constructor inside the class (also returning null when failed). But I thought to return null we can leave the constructor early, thus stopping the object from being made. This doesn’t work, so is this even possible?

Here is my new constructor:


  // ------------------------------

  Formula  (String in_) {
    // parseStringToFormula

    Formula myFormula=null;

    fullText=in_;

    if (in_.charAt(0)!='=') {
      // this  =  null;
      return;       // !!!!!!!!!!!!
    }
   
    ........
    ......

Thanks to all!

Warmest regards and a great 2025,

Chrisir

1 Like

You might try out to throw an Exception in order to interrupt the class instantiation.

3 Likes

yeah, but there is no real error. Can I just say throw?
can you post an example?

1 Like

This is an example that throws an unchecked exception, which doesn’t require a try/catch block:

class Formula {
  String fullText;

  Formula(final String input) {
    if (input.charAt(0) != '=') throw new IllegalArgumentException(
      input + " must begin with the '=' character!"
    );

    fullText = input;
  }
}

Same as above, but it throws a checked exception which requires a try/catch block:

class Formula {
  String fullText;

  Formula(final String input) throws java.text.ParseException {
    if (input.charAt(0) != '=') throw new java.text.ParseException(
      input + " must begin with the '=' character!", 0
    );

    fullText = input;
  }
}
3 Likes

Thanks a lot! Gonna test it.

1 Like