Can the constructor abort instantiation?

爷,独闯天下 提交于 2019-12-21 23:35:51

问题


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.


回答1:


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();



回答2:


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.




回答3:


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




回答4:


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.




回答5:


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.



来源:https://stackoverflow.com/questions/9965300/can-the-constructor-abort-instantiation

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!