Java IllegalStateException
Example
Read from a Scanner after it is closed, and catch the exception:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner myObj = new Scanner("Hello World");
myObj.close();
try {
System.out.println(myObj.nextLine());
} catch (IllegalStateException e) {
System.out.println("Error: the scanner is closed.");
}
}
}
Definition and Usage
An IllegalStateException happens when you call a method at a time when the object is not ready for it, for example when you read from a Scanner after it is closed.
Another common case is when you call remove() on an Iterator before you call next().
Related Pages
Java Exceptions (try...catch) Tutorial
❮ Errors & Exceptions