Junior
Is it possible to declare throws Exception in an overridden clone() method, considering it has @Override annotation?
sobes.tech AI
Answer from AI
In Java, when overriding the clone() method declared in the Object class with the signature:
protected Object clone() throws CloneNotSupportedException
you cannot expand the list of checked exceptions. That is, if you override this method, you can:
- Not declare
throwsat all, - Or declare
throws CloneNotSupportedExceptionor its subclass, - But you cannot add
throws Exception, as it is a more general exception.
Attempting to declare throws Exception will result in a compile-time error because a method annotated with @Override must strictly match or narrow the signature of the base method.
An example of a correct override:
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
Therefore, declaring throws Exception is not allowed.