dazito
dazito

Reputation: 7980

Throwing an Exception in the object constructor

Lets say I've this code:

public class MyClass {

    public final static int valueA = 0;
    public final static int valueB = 1;

    private int parameter = -1;

    public MyClass(int parameter) {

        if(parameter != valueA && parameter != valueB) {
            throw new IllegalArgumentException("Exception description here");
        }

        this.parameter = parameter;
    }

}

Is this a best practice? Or is there a better way to grantee that whatever the value passed on the constructor it has the same value as one of those variables?

Upvotes: 1

Views: 92

Answers (2)

Eran
Eran

Reputation: 393771

The Java API contains many classes that throw exceptions in their constructors, so there's nothing wrong with that.

Example :

In java.net.URI class :

public URI(String str) throws URISyntaxException {
    new Parser(str).parse(false);
}

In java.util.ArrayList class :

public ArrayList(int initialCapacity) {
    super();
    if (initialCapacity < 0)
        throw new IllegalArgumentException("Illegal Capacity: "+
                                           initialCapacity);
    this.elementData = new Object[initialCapacity];
}

Upvotes: 6

Hypino
Hypino

Reputation: 1248

Maybe you should look into Enums.

public enum MyEnum {

    A(0),
    B(1);

    private int parameter;

    public MyEnum(int parameter)
    {
        this.parameter = parameter;
    }

}

Basically, this forces that you can only have the object with the parameter = 0,or parameter = 1. However, this also only allows ONE instance of each type (0, 1, etc...), so this may not work depending on your use case.

Upvotes: 6

Related Questions