2

I want to make tests in a constructor to find out if it is currently a good idea to instantiate the object or not, with the given parameters. But how could I abort and return a warning from a constructor to the new statement? Must such tests instead be done by the caller before each "new" statement? I thought that the constructor would be a good place for it.

Tombola
  • 1,121
  • 5
  • 15
  • 25

5 Answers5

11

You could use a factory object instead. This could then run your checks and return the instansiated object, or null. This would probably be more efficient than an exception.

MyObject myObject = MyObjectFactory.createMyObject();
GavinCattell
  • 3,757
  • 19
  • 22
7

Yes, you throw an exception in the constructor.

In java you usually throw an IllegalArgumentException if one of the arguments were wrong which is a common thing to do really as a guard statement:

public class Roman {

    public Roman(int arabic) {

        // "Guard statement" in the beginning of the constructor that
        // checks if the input is legal
        if (arabic < 0) {
            throw new IllegalArgumentException("There are no negative roman numerals");
        }

        // Continue your constructor code here

    }

}

If you don't want exceptions you can do as GavinCatelli's answer and create a factory method that returns null if the object won't be "correct".

public class RomanFactory {

    public static Roman getSafeRoman(int a) {
        Roman r;
        try {
            r = new Roman(a);
        } catch(IllegalArgumentException e) {
            r = null;
        }
        return r;
    }

}

You do have to check for null's though, or else the program might crash with NullPointerException.

Community
  • 1
  • 1
Spoike
  • 116,468
  • 43
  • 136
  • 157
3

The only sure way to abort object construction is to throw an Exception before completion of the constructor

John Vint
  • 38,644
  • 6
  • 74
  • 105
1

You can have the constructor throw an exception if the parameters are invalid.

If it's just a question of input validity that a caller should be able to check itself, you should throw a RuntimeException. If it's something that a caller won't necessarily be able to control, the constructor should throw a checked exception; note that this will require all code which calls the constructor to handle or declare the exception.

Taymon
  • 23,632
  • 9
  • 61
  • 83
0

Make your own class of exception and accordingly pass the message based on the parameters that are passed to the constructor. Thus throw this exception from the constructor.

Noroi
  • 71
  • 7