Class IllegalComponentStateException in Java

Class IllegalComponentStateException in Java

An Exception indicating that a Component was not in an appropriate state to perform requested action.

IllegalComponentStateException is a child class of RunTimeException. Hence coders do not need to bother to use a try-catch block. Catching this exception is not a good practice.

IllegalComponentStateExceptio is also child class of IllegalStateException. This exception occurs when we try to do some inappropriate activities in a component.

In which scenario IllegalComponentStateException may occur. There can be three scenarios where IllegalComponentStateException occurs-

  • If coder calls setCaretPosition() to set a cursor position before the per component exists.
  • If coder calls getLocale() to get the locale of the component but neither the component the container has one.
  • If coder calls getLocationOnScreen() for a component that is not visible.

The Hierarchy of IllegalComponentStateException is as follows

IllegalComponentStateException
IllegalComponentStateException

The structure of the class IllegalComponentStateException is given by

public class java.awt.IllegalComponentStateException
extends java.lang.IllegalStateException {
// Constructors
public IllegalComponentStateException();//Constructs the exception object with no detail message.
public IllegalComponentStateException (String s);//Constructs the exception object with the given detail message.
}

Below is an example of IllegalComponentStateException. In this case, as the corresponding text field, peer does not exists and the coder tries to call setCaretPosition() method


import Java.awt.TextField;
public class IllegalCompoentStateExceptionTest{
public static void main(String ar[]){
new TextField().setCaretPosition(10);
}
}

 In this case the setCaretPosition() throws an IllegalComponentstateException.

Share and Enjoy !

See also  ArithmeticException in Java

Leave a Reply

Your email address will not be published. Required fields are marked *