Apr 5, 2011

Learning from CloneNotSupportedException

Learning from CloneNotSupportedException

CloneNotSupportedException can be taken as an example of custom exception. We can see the source code of this exception class to see how we can create more custom exceptions:

/*
* %W% %E%
*
* Copyright (c) 2006, Oracle and/or its affiliates. All rights reserved.
* ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/

package java.lang;

/**
* 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. 
* 
* Applications that override the clone method can also 
* throw this exception to indicate that an object could not or 
* should not be cloned.
*
* @author  unascribed
* @version %I%, %G%
* @see     java.lang.Cloneable
* @see     java.lang.Object#clone()
* @since   JDK1.0
*/

public
class CloneNotSupportedException extends Exception {
/**
* Constructs a CloneNotSupportedException with no 
* detail message. 
*/
public CloneNotSupportedException() {
super();
}

/**
* Constructs a CloneNotSupportedException with the 
* specified detail message. 
*
* @param   s   the detail message.
*/
public CloneNotSupportedException(String s) {
super(s);
}
}

There we can see that the CloneNotSupportedException extends Exception class which makes this class as a checked exception. Now the question comes as to how to use this exception.

For usage, we go to the clone method of the Object class and we see that the javadoc of this method states that the CloneNotSupportedException is thrown if the Cloneable interface is not implemented by the class on which clone method is invoked.

Similarly, if we want to create our custom exception for scenarios not captured by the exceptions present in the Java API, we need to extend the Exception class or any of its subclass.


1 comment: