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?

Sarah Aziziyan
  • 498
  • 9
  • 22
Jacinto Resende
  • 343
  • 2
  • 13
  • 1
    Why do you want to call `this()`? – assylias Oct 12 '17 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.` – LenglBoy Oct 12 '17 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. – AxelH Oct 12 '17 at 10:58
  • https://stackoverflow.com/questions/5749218/building-a-copy-constructor-in-java – assylias Oct 12 '17 at 10:59
  • 1
    Possible duplicate of [Java call constructor from constructor](https://stackoverflow.com/questions/12880443/java-call-constructor-from-constructor) – vichu Oct 12 '17 at 11:14

1 Answers1

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
}
LenglBoy
  • 1,451
  • 1
  • 10
  • 24