Java CloneNotSupportedException 及其示例

2024年9月10日 | 阅读 2 分钟

在 Java 中,CloneNotSupportedException 是一个指示克隆对象失败的异常,因为该对象未实现 Cloneable 接口。Cloneable 接口是一个标记接口,用于指示对象可以被克隆。当克隆一个未实现 Cloneable 的对象时,Java 会抛出 CloneNotSupportedException。

层级结构

这是 **CloneNotSupportedException** 类的继承层次结构

从继承层次结构可以看出,**CloneNotSupportedException** 扩展了 **Exception** 类,而 **Exception** 类又扩展了 **Throwable** 类。Java 程序可以捕获和处理 CloneNotSupportedException,这是一种异常类型。

可以使用 try-catch 块来处理此异常,或者可以使用 throws 关键字在方法的签名中指定抛出它。

语法

Java 中 **CloneNotSupportedException** 的语法是

CloneNotSupportedException 示例

文件名: Dog.java

输出

Dog [Breed=Labrador Retriever, Age=3]
Cloning not supported: Cloning not supported for class Dog.

java.lang.CloneNotSupportedException: Cloning not supported for class Dog.
	at Dog.clone(CloneNotSupportedExceptionDemo.java:22)
	at CloneNotSupportedExceptionDemo.main(CloneNotSupportedExceptionDemo.java:36)