logo

Java에서 IllegalStateException을 해결하는 방법은 무엇입니까?

예외 프로그램에서 발생하는 원치 않는 예상치 못한 오류입니다. 대부분의 경우 코드에 오류가 있지만 처리할 수 있는 경우 예외가 발생합니다. 이는 코드의 정상적인 흐름을 방해합니다.

예를 들어, 사용자가 잘못된 정보를 입력한 경우, 코드가 원격지에 있는 파일을 읽을 수 없는 경우, 통신 도중 네트워크 연결이 끊어진 경우 코드에서 예외가 발생합니다.

현지 날짜

Java의 IllegalStateException

IllegalStateException RuntimeException 클래스의 하위 클래스이므로 확인되지 않은 예외입니다. 프로그래머나 API 개발자가 명시적으로 발생합니다. 메소드 호출이 불법이거나 잘못된 시간에 메소드가 호출되는 경우 발생합니다.

예를 들어, 스레드를 시작한 후에는 동일한 스레드를 다시 시작할 수 없습니다. 그렇게 하려고 하면 런타임 예외가 발생합니다. 즉, IllegalStateException .

예외 5월 일반적으로 컬렉션 프레임워크로 작업할 때 코드에서 발생합니다. List, Queue, Maps, Tree는 컬렉션 중 일부입니다. 이 중에서 목록과 대기열은 특정 조건에서 잘못된 상태 예외를 발생시키는 경향이 있습니다.

참고: IllegalStateException 예외는 컬렉션 프레임워크에만 국한되지 않습니다.

몇 가지 시나리오를 살펴보겠습니다. IllegalStateException 던져질 것이다.

예시 1:

다음 Java 프로그램은 run() 메소드가 이미 실행 중일 때 start() 메소드를 호출하려고 하는 상황을 보여줍니다.

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

산출:

Java에서 null을 확인하십시오.
Java에서 IllegalStateException을 해결하는 방법

IllegalStateException에 대한 솔루션

피하기 위해 java.lang.IllegalStateException Java에서는 부적절하거나 불법적인 시간에 코드의 모든 메서드가 호출되지 않도록 주의해야 합니다.

예 1과 2에 대한 솔루션:

start() 메소드를 두 번 이상 호출한 위의 예제 1과 2를 고려하십시오. 한 번만 호출하면 이 예외가 발생하지 않습니다. 스레드를 시작한 후에 start() 메서드가 호출되지 않기 때문입니다.

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

산출:

Java에서 IllegalStateException을 해결하는 방법