1

I have a class constructor and I need to perform a clone. From what I've read the best choice is to use a copy constructor, just like in C++. However, I've got an issue. If my "regular" constructor throws exceptions and such exceptions aren't even possible in a "copy constructor" how to I implement a try-catch if the first statement must be this.

public class X
{
   public X() throws MyException
   {
   }

   public X(final X original)
   {
      try {
         this();
      } catch (MyException e)
      {
      }
   }
}   

Is the only option add throws MyException to copy constructor?

5
  • 1
    Why do you want to call this()? Commented Oct 12, 2017 at 10:55
  • if you call this() you just init a new empty object. if you want a real copy with all values you should add a null-checking to x(final X original) and then copy each field from original to this.<field> Commented Oct 12, 2017 at 10:56
  • "If my "regular" constructor throws exceptions and such exceptions aren't even possible in a "copy constructor"" Even if you don't see a way, if a throws is present, assume you need to managed it or rethrow the exception. Don't assume an exception defined in a method declaration can't happen. If I need to update your class and I see the exception was defined, I know that this was expected so I can't throw that exception in my updated version without having to worry. The contract was already signed. Commented Oct 12, 2017 at 10:58
  • stackoverflow.com/questions/5749218/… Commented Oct 12, 2017 at 10:59
  • 1
    Possible duplicate of Java call constructor from constructor Commented Oct 12, 2017 at 11:14

1 Answer 1

0

Copy all data to a new instance by constructor could look like this:

public class X
{
   // some Fields....
   int a, b, c;

   public X() { }

   public X(final X originalX) throws InvalidArgumentException
   {
      if(originalX == null) {
        throw new InvalidArgumentException("originalX should not be null!");
      }
      this.a = originalX.getA();
      //...
   }
   // getter-setter....
}

And it´s called like this in main() or where ever else:

// x_1 is filles with Data...
X x_2;
try {
    x_2 = new X(x_1);
} catch(InvalidArgumentException ex) {
    LOG.reportError(ex.getMessage());
    x_2 = new X();  // prevent NullPointer for usage afterwards
}
Sign up to request clarification or add additional context in comments.

3 Comments

true, but the question is about "catching the exception from this()"
but calling this() is doing nothing and shouldn´t be required for his usage.
Maybe, but this is what your answer should explain ;) What if the constructor have a init() statement, what can he do ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.