logo

Cum se rezolvă IllegalStateException în Java?

Un excepție este o eroare nedorită și neașteptată aruncată în program. De cele mai multe ori, apare o excepție atunci când există o eroare în codul nostru, dar poate fi gestionată. Întrerupe fluxul normal al codului.

De exemplu, codul aruncă o excepție dacă utilizatorul a introdus informații nevalide, dacă codul nu poate citi fișierul aflat la distanță sau dacă conexiunea la rețea se pierde în mijlocul comunicării.

IllegalStateException în Java

IllegalStateException este subclasa clasei RuntimeException și, prin urmare, este o excepție neverificată. Este creat de programator sau de dezvoltatorul API în mod explicit. Este aruncat atunci când un apel de metodă este ilegal sau o metodă este apelată la un moment incorect.

De exemplu, odată ce începem un thread, nu putem reporni același thread din nou; dacă încercăm să facem asta, se aruncă o excepție de rulare, adică IllegalStateException .

Exceptia Mai apar în cod, de obicei, atunci când lucrăm cu cadrul Collections. Lista, Coada, Hărți, Arborele sunt câteva dintre colecții. Dintre acestea, Listă și Cozile tind să arunce excepția de stat ilegală în condițiile specifice.

Notă: excepția IllegalStateException nu se limitează doar la cadrul de colecții.

Să vedem câteva dintre scenariile în care IllegalStateException va fi aruncat.

Exemplul 1:

Următorul program Java descrie situația în care încercăm să apelăm metoda start() când metoda run() este deja în execuție.

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;>

Ieșire:

Cum se rezolvă IllegalStateException în Java

Soluție pentru IllegalStateException

Pentru a evita java.lang.IllegalStateException în Java ar trebui să avem grijă ca orice metodă din codul nostru să nu poată fi apelată la un moment nepotrivit sau ilegal.

Soluția de exemplu 1 și 2:

Luați în considerare exemplele de mai sus 1 și 2 în care am apelat metoda start() de mai multe ori. Dacă o numim o singură dată, nu vom primi această excepție. Deoarece metoda start() nu este apelată după pornirea firului.

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;>

Ieșire:

Cum se rezolvă IllegalStateException în Java