Java : IllegalStateException with Examples
IllegalStateException (Java SE 21 & JDK 21) with Examples.
You will find code examples on most IllegalStateException methods.
Summary
final var queue = new ArrayBlockingQueue<String>(3);
System.out.println(queue.remainingCapacity()); // 3
queue.add("aaa");
queue.add("bbb");
queue.add("ccc");
System.out.println(queue); // [aaa, bbb, ccc]
System.out.println(queue.remainingCapacity()); // 0
try {
queue.add("ddd");
} catch (IllegalStateException e) {
System.out.println(e);
}
// Result
// ↓
//java.lang.IllegalStateException: Queue full
class Sample implements Closeable {
private boolean closed;
@Override
public void close() {
closed = true;
}
public String read() {
if (closed) {
throw new IllegalStateException("Closed!");
}
return "abcd";
}
}
final var sample = new Sample();
System.out.println(sample.read()); // abcd
sample.close();
try {
final var ret = sample.read();
} catch (IllegalStateException e) {
System.out.println(e);
}
// Result
// ↓
//java.lang.IllegalStateException: Closed!
Constructors
IllegalStateException ()
final var e = new IllegalStateException();
System.out.println(e); // java.lang.IllegalStateException
IllegalStateException (String s)
final var e = new IllegalStateException("abcde");
System.out.println(e); // java.lang.IllegalStateException: abcde
System.out.println(e.getMessage()); // abcde
IllegalStateException (String message, Throwable cause)
final var cause = new IllegalStateException("XYZ");
final var e = new IllegalStateException("abcde", cause);
System.out.println(e); // java.lang.IllegalStateException: abcde
System.out.println(e.getMessage()); // abcde
System.out.println(e.getCause()); // java.lang.IllegalStateException: XYZ
System.out.println(e.getCause().getMessage()); // XYZ
IllegalStateException (Throwable cause)
final var cause = new IllegalStateException("XYZ");
final var e = new IllegalStateException(cause);
System.out.println(e); // java.lang.IllegalStateException: java.lang.IllegalStateException: XYZ
System.out.println(e.getMessage()); // java.lang.IllegalStateException: XYZ
System.out.println(e.getCause()); // java.lang.IllegalStateException: XYZ
System.out.println(e.getCause().getMessage()); // XYZ
Methods declared in Throwable
addSuppressed, fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, getSuppressed, initCause, printStackTrace, printStackTrace, printStackTrace, setStackTrace, toString
Please see the link below.
Related posts
- API Examples
- Error
- Exception
- RuntimeException
- ArithmeticException
- ArrayIndexOutOfBoundsException
- ArrayStoreException
- CancellationException
- ClassCastException
- ConcurrentModificationException
- DateTimeException
- DateTimeParseException
- IllegalArgumentException
- IndexOutOfBoundsException
- NoSuchElementException
- NullPointerException
- PatternSyntaxException
- StringIndexOutOfBoundsException
- UnsupportedOperationException
- Throwable