CKTIS / Java
InterruptedException — handling thread interruption
InterruptedException is a checked exception signaling interruption of an operation such as Thread.sleep. Learn how the exception differs from the interrupt flag and how to preserve the signal when handling it.
Version: Java SE 21; repository runtime, production runtime not attested
Syntax
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return;
}java.lang.InterruptedException extends Exception and is a checked exception. Code must catch it or declare it in the method's throws clause. If the method contract permits it, use throws InterruptedException or declare an applicable supertype, for example with throws Exception. The exception signals interruption before or during an operation, for example Thread.sleep, Object.wait, or Thread.join. Its constructors are InterruptedException() and InterruptedException(String s).
Interruption is a cooperative signal, not forced thread termination. Calling interrupt() does not always cause an exception. When sleep, wait, or join throws InterruptedException, the interrupt flag is cleared. isInterrupted() reads it without changing it; Thread.interrupted() reads and clears the current thread's flag.
Usually, propagate the exception. If the method contract does not allow this, restore the flag with Thread.currentThread().interrupt() and stop the current task or return to the caller. Do not silently ignore the exception without a deliberate interruption policy.
The example sets the flag before Thread.sleep(1000), so it does not depend on scheduling multiple threads. It demonstrates clearing and restoring the flag. The documentation scope is Java SE 21; the production runtime version has not been attested.
Examples
public class Main {
public static void main(String[] args) {
Thread current = Thread.currentThread();
current.interrupt();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println("caught: " + current.isInterrupted());
current.interrupt();
System.out.println("restored: " + current.isInterrupted());
}
}
}Result
caught: false restored: true
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.