Java : CloneNotSupportedException - API Examples

CloneNotSupportedException (Java SE 19 & JDK 19) API Examples.
You will find code examples on most CloneNotSupportedException methods.


Summary

Thrown to indicate that the clone method in class Object has been called to clone an object, but that the object's class does not implement the Cloneable interface.

Class diagram

Please see also : Cloneable

record Sample(int num, String str) {
    @Override
    public Sample clone() throws CloneNotSupportedException {
        return (Sample) super.clone();
    }
}

try {
    final var sample = new Sample(100, "abc");
    final var cloned = sample.clone();

    System.out.println("Cloned! : " + cloned);

} catch (CloneNotSupportedException e) {
    System.out.println("CloneNotSupportedException!");
}

// Result
// ↓
//CloneNotSupportedException!
record Sample(int num, String str) implements Cloneable {
    @Override
    public Sample clone() throws CloneNotSupportedException {
        return (Sample) super.clone();
    }
}

try {
    final var sample = new Sample(100, "abc");
    final var cloned = sample.clone();

    System.out.println("Cloned! : " + cloned);

} catch (CloneNotSupportedException e) {
    System.out.println("CloneNotSupportedException!");
}

// Result
// ↓
//Cloned! : Sample[num=100, str=abc]

Constructors

CloneNotSupportedException ()

Constructs a CloneNotSupportedException with no detail message.

final var e = new CloneNotSupportedException();
System.out.println(e); // java.lang.CloneNotSupportedException

CloneNotSupportedException (String s)

Constructs a CloneNotSupportedException with the specified detail message.

final var e = new CloneNotSupportedException("abcde");
System.out.println(e); // java.lang.CloneNotSupportedException: abcde
System.out.println(e.getMessage()); // abcde

Methods declared in Throwable

addSuppressed, fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, getSuppressed, initCause, printStackTrace, printStackTrace, printStackTrace, setStackTrace, toString

Please see the link below.


Related posts

To top of page