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.
5 Answers
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();

- 3,863
- 20
- 22
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.
The only sure way to abort object construction is to throw an Exception before completion of the constructor

- 39,695
- 7
- 78
- 108
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.

- 24,950
- 9
- 62
- 84
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.

- 71
- 7