1

I have the following code in the mClass constructor:

public mClass(Context ctx) {
    super();
    this.ctx = ctx;
}

The context can't be null because its necesary for the object operation. So if I allow the creation of an new mClass(null) it will break later.

I'd like to crash when the object is create because is when the incorrect situation is happening. Whats the standard way of doing this?

For example making

public mClass(Context ctx) {
    super();
    if(ctx==null) throw new Exception ("....");
    this.ctx = ctx;
}

forces to declare the method as exception thrower and I dont wan't to do this because passing a null value is not usual

Addev
  • 31,819
  • 51
  • 183
  • 302

3 Answers3

7

Throw java.lang.IllegalArgumentException,

which is a runtime exception so you don't need to forcibly handle this, and if it is thrown application will get crashed (if it is not handled)

jmj
  • 237,923
  • 42
  • 401
  • 438
1

You can avoid throwing an exception from the constructor all together by making your class' constructor private thereby ensuring clients can only create instances of your class via a builder. The builder can check the validity of the supplied constructor dependencies before constructing an object as shown below:

public class MyClass {

    public static class MyClassBuilder {
        private Context ctx;

        public MyClassBuilder setContext(Context ctx) {
            this.ctx = ctx;

            return this;
        }

        public MyClass build() {
            if(ctx==null) {
                throw new IllegalArgumentException ("");
            } else {
                return new MyClass(this.ctx);
            }
        }
    }

    private final Context ctx;

    private MyClass(Context ctx) {
        super();
        this.ctx = ctx;
    }
}
Community
  • 1
  • 1
munyengm
  • 15,029
  • 4
  • 24
  • 34
1

If MyClass cannot be responsible for constructing its own Context you should inject it like you do. Throwing a RuntimeException or any subclass will do for a null-check, but IllegalArgumentException is most appropriate here.

Do not forget to make the ctx field final, it will make your code more robust.

Bart Swennenhuis
  • 324
  • 2
  • 11