logo

¿Cómo resolver IllegalStateException en Java?

Un excepción es un error no deseado e inesperado que se produce en el programa. La mayoría de las veces, se produce una excepción cuando hay un error en nuestro código pero se puede solucionar. Interrumpe el flujo normal del código.

Por ejemplo, el código genera una excepción si el usuario ingresó información no válida, si el código no puede leer el archivo ubicado en el lugar remoto o si la conexión de red se pierde en medio de la comunicación.

IllegalStateException en Java

Excepción de estado ilegal es la subclase de la clase RuntimeException y, por lo tanto, es una excepción no comprobada. Lo genera explícitamente el programador o el desarrollador de API. Se lanza cuando una llamada a un método es ilegal o se llama a un método en el momento incorrecto.

Por ejemplo, una vez que iniciamos un hilo, no podemos reiniciar el mismo hilo nuevamente; si intentamos hacer eso, arroja una excepción de tiempo de ejecución, es decir, Excepción de estado ilegal .

La excepción puede Surgen en el código generalmente cuando trabajamos con el marco de Colecciones. La Lista, Cola, Mapas, Árbol son algunas de las colecciones. De estos, Lista y Colas tienden a generar la excepción de estado ilegal en condiciones específicas.

Nota: La excepción IllegalStateException no se limita solo al marco de Colecciones.

Veamos algunos de los escenarios donde el Excepción de estado ilegal será arrojado.

Ejemplo 1:

El siguiente programa Java describe la situación en la que intentamos llamar al método start() cuando el método run() ya se está ejecutando.

IllegalStateExceptionTest1.java

 // importing necessary packages import java.io.*; import java.util.*; // creating a new thread in NewThread class by extending Thread class // below class is acts as a helper class class NewThread extends Thread { // declaring the run() method // executes 3 times using for loop public void run() { for (int i = 0; i <3; i++) { displaying the text system.out.println('this is example of illegalstateexception'); } creating main class public illegalstateexceptiontest1 method static void main(string[] args) object above helper newthread t="new" newthread(); starting created thread using start() t.start(); thread'); again when it already running this gives an exception < pre> <p> <strong>Output:</strong> </p> <img src="//techcodeview.com/img/java-tutorial/19/how-resolve-illegalstateexception-java.webp" alt="How to resolve IllegalStateException in Java"> <h3>Example 2:</h3> <p>The following code depicts the situation where we call the start() method on a thread when the execution of run() method is over.</p> <p> <strong>IllegalStateExceptionTest2.java</strong> </p> <pre> // importing necessary packages import java.io.*; import java.util.*; // creating a new thread in NewThread class by extending Thread class // below class is acts as a helper class class NewThread extends Thread { // declaring the run() method // executes 3 times using for loop public void run() { for (int i = 0; i <3; i++) { displaying the text system.out.println('this is example of illegalstateexception'); } creating main class public illegalstateexceptiontest2 method static void main(string[] args) object above helper newthread t="new" newthread(); starting created thread using start() t.start(); try system.out.println('main going to sleep'); putting on sleep for 4000ms t.sleep(4000); awaken'); catch (exception e) system.out.println(e); message thread'); calling over a dead this also gives an exception < pre> <p> <strong>Output:</strong> </p> <img src="//techcodeview.com/img/java-tutorial/19/how-resolve-illegalstateexception-java-2.webp" alt="How to resolve IllegalStateException in Java"> <h3>Example 3:</h3> <p>The following code explains the situation where we are using the remove() method to remove the element from the ArrayList, before moving to the first element.</p> <p> <strong>IllegalStateExceptionTest3.java</strong> </p> <pre> // importing necessary packages import java.util.ArrayList; import java.util.ListIterator; // creating the main class public class IllegalStateExceptionTest3 { // main method public static void main(String args[]) { // instantiating the object of ArrayList ArrayList list = new ArrayList(); // adding elements to the ArrayList list.add(&apos;Nirnay&apos;); list.add(&apos;Anu&apos;); list.add(&apos;Swara&apos;); list.add(&apos;Pavan&apos;); // creating the iterator object to iterate the list ListIterator it = list.listIterator(); // removing the element without moving to first position // gives an exception it.remove(); } } </pre> <p> <strong>Output:</strong> </p> <img src="//techcodeview.com/img/java-tutorial/19/how-resolve-illegalstateexception-java-3.webp" alt="How to resolve IllegalStateException in Java"> <h2>Solution for the IllegalStateException</h2> <p>To avoid the <strong>java.lang.IllegalStateException</strong> in Java we should take care that any method in our code cannot be called at inappropriate or illegal time.</p> <p> <strong>Solution for example 1 and 2:</strong> </p> <p>Consider the above example 1 and 2 where we have called the start() method more than once. If we call it only once, we will not get this exception. Because start() method is not called after starting the thread.</p> <p> <strong>IllegalStateExceptionSolution.java</strong> </p> <pre> // importing necessary packages import java.io.*; import java.util.*; // creating a new thread in NewThread class by extending Thread class // below class is acts as a helper class class NewThread extends Thread { // declaring the run() method // executes 3 times using for loop public void run() { for (int i = 0; i <3; i++) { displaying the text system.out.println('this is example of illegalstateexception'); } creating main class public illegalstateexceptionsolution method static void main(string[] args) object above helper newthread t="new" newthread(); starting created thread using start() t.start(); try system.out.println('main going to sleep'); putting on sleep for 4000ms t.sleep(4000); awaken'); catch (exception e) system.out.println(e); message thread'); we do not call again < pre> <p> <strong>Output:</strong> </p> <img src="//techcodeview.com/img/java-tutorial/19/how-resolve-illegalstateexception-java-4.webp" alt="How to resolve IllegalStateException in Java"> <p> <strong>Solution for Example 3:</strong> </p> <p>The remove() method of the ArrayList class is used to remove the last element after calling the next() method.</p> <ul> <li>After removing element at current index we have to move next element to remove it. (for every call of the next() method, we have to invoke the remove() method only once).</li> <li>As the initial position of list will be before the first element, we cannot call the remove() method without calling the next() method.</li> </ul> <p>In order to prevent the exception we need to follow the above steps in our Java code.</p> <p> <strong>IllegalStateExceptionSolution2.java</strong> </p> <pre> // importing necessary packages import java.util.ArrayList; import java.util.ListIterator; // creating the main class public class IllegalStateExceptionSolution2 { // main method public static void main(String args[]) { // instantiating the object of ArrayList ArrayList list = new ArrayList(); // adding elements to the ArrayList list.add(&apos;Nirnay&apos;); list.add(&apos;Anu&apos;); list.add(&apos;Swara&apos;); list.add(&apos;Pavan&apos;); // creating the iterator object to iterate the list ListIterator it = list.listIterator(); // using the next() method before remove() it.next(); // removing the element without moving to first position it.remove(); // displaying new ArrayList System.out.println(&apos;List after removing the first element: &apos; + list); } } </pre> <p> <strong>Output:</strong> </p> <img src="//techcodeview.com/img/java-tutorial/19/how-resolve-illegalstateexception-java-5.webp" alt="How to resolve IllegalStateException in Java"> <hr></3;></pre></3;></pre></3;>

Producción:

Cómo resolver IllegalStateException en Java

Solución para la excepción IllegalStateException

Para evitar el java.lang.IllegalStateException En Java debemos tener cuidado de que ningún método de nuestro código pueda ser invocado en un momento inadecuado o ilegal.

Solución por ejemplo 1 y 2:

Considere los ejemplos 1 y 2 anteriores donde hemos llamado al método start() más de una vez. Si lo llamamos sólo una vez, no obtendremos esta excepción. Porque el método start() no se llama después de iniciar el hilo.

IllegalStateExceptionSolution.java

 // importing necessary packages import java.io.*; import java.util.*; // creating a new thread in NewThread class by extending Thread class // below class is acts as a helper class class NewThread extends Thread { // declaring the run() method // executes 3 times using for loop public void run() { for (int i = 0; i <3; i++) { displaying the text system.out.println(\'this is example of illegalstateexception\'); } creating main class public illegalstateexceptionsolution method static void main(string[] args) object above helper newthread t="new" newthread(); starting created thread using start() t.start(); try system.out.println(\'main going to sleep\'); putting on sleep for 4000ms t.sleep(4000); awaken\'); catch (exception e) system.out.println(e); message thread\'); we do not call again < pre> <p> <strong>Output:</strong> </p> <img src="//techcodeview.com/img/java-tutorial/19/how-resolve-illegalstateexception-java-4.webp" alt="How to resolve IllegalStateException in Java"> <p> <strong>Solution for Example 3:</strong> </p> <p>The remove() method of the ArrayList class is used to remove the last element after calling the next() method.</p> <ul> <li>After removing element at current index we have to move next element to remove it. (for every call of the next() method, we have to invoke the remove() method only once).</li> <li>As the initial position of list will be before the first element, we cannot call the remove() method without calling the next() method.</li> </ul> <p>In order to prevent the exception we need to follow the above steps in our Java code.</p> <p> <strong>IllegalStateExceptionSolution2.java</strong> </p> <pre> // importing necessary packages import java.util.ArrayList; import java.util.ListIterator; // creating the main class public class IllegalStateExceptionSolution2 { // main method public static void main(String args[]) { // instantiating the object of ArrayList ArrayList list = new ArrayList(); // adding elements to the ArrayList list.add(&apos;Nirnay&apos;); list.add(&apos;Anu&apos;); list.add(&apos;Swara&apos;); list.add(&apos;Pavan&apos;); // creating the iterator object to iterate the list ListIterator it = list.listIterator(); // using the next() method before remove() it.next(); // removing the element without moving to first position it.remove(); // displaying new ArrayList System.out.println(&apos;List after removing the first element: &apos; + list); } } </pre> <p> <strong>Output:</strong> </p> <img src="//techcodeview.com/img/java-tutorial/19/how-resolve-illegalstateexception-java-5.webp" alt="How to resolve IllegalStateException in Java"> <hr></3;>

Producción:

Cómo resolver IllegalStateException en Java