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?
this()?this()you just init a new empty object. if you want a real copy with all values you should add a null-checking tox(final X original)and then copy each field from original tothis.<field>throwsis 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.