Throw Exception and then Call Constructor?

So, I am creating a test library that I will use mainly for personal use, but I have a question.

With Java, if you have 2 or more constructors in your class, if you want to call one from the other, this should be the first thing you do. This is problematic for me since I have the following setup.

public Constructor(TypeA a, TypeB b, TypeC c) { if (c.getData() == null) throw new IllegalArgumentException(""); this(a, b, c.getOtherData()); } public Constructor(TypeA a, TypeB b, TypeD d) { // stuff happens } 

How can I do this, avoiding this, the "constructor error should be the first operation in the constructor" error?

+5
source share
5 answers

You cannot do what you want with the constructors. Instead, use the static factor method as follows:

 public static TypeThing buildMyThing(TypeA a, TypeB b, TypeC c) { if (c.getData() == null) throw new IllegalArgumentException(""); return new TypeThing(a, b, c.getOtherData()); } public Constructor(TypeA a, TypeB b, TypeD d) { // stuff happens } 
+4
source

One option (possibly bad): Check getData == null and throw the exception as first thing in c.getOtherData () `. This will be the first executable method.

Another option: Have a method like

 helper() { if (getData() == null) throw new Exception(); return getOtherData(); } 

and from you constructor call c.helper() instead of c.getOtherData()

+3
source

How to create a static factory method?

 public static Constructor newInstance(TypeA a, TypeB b, TypeC c) { if (c.getData() == null) throw new IllegalArgumentException(""); return new Constructor(a, b, c); } private Constructor(TypeA a, TypeB b, TypeC c) { this(a, b, c.getOtherData()); } private Constructor(TypeA a, TypeB b, TypeD d) { // stuff happens } 
+2
source

You may have an additional private constructor. I assume that you have simplified the code here too much. You say that if something is zero, then drop it - otherwise you are something else.

 public Constructor(TypeA a, TypeB b, TypeC c) { this(a, b, c.getData(), c.getOtherData()); //calls the private ctor } public Constructor(TypeA a, TypeB b, TypeD d) { // stuff happens } private Constructor(TypeA a, TypeB b, TypeD d1, TypeD d2) { // stuff happens } 

or you can just pass TypeC

  private Constructor(TypeA a, TypeB b, TypeC) { // now do you null check here. } 

Java sometimes causes some pain! and then this rule is one of them. In a specific answer to your question about a compilation error - you cannot :(

0
source

Try moving the exception sent to the beginning of the second constructor. It will achieve the same. If there are several paths to this constructor, you can make an additional parameter that signals a logical path.

0
source

All Articles