Java InterruptedException
Example
Interrupt a thread before it sleeps, and catch the exception:
public class Main {
public static void main(String[] args) {
Thread.currentThread().interrupt();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println("The thread was interrupted.");
}
}
}
Definition and Usage
An InterruptedException happens when a thread (a part of the program that can run at the same time as other parts) is interrupted while it sleeps or waits, for example in Thread.sleep().
It is a checked exception (Java requires you to catch it, or to declare it with throws). In the example, the thread interrupts itself first, so sleep() throws the exception at once.
Tip: Read more about threads in our Java Threads Tutorial.
Related Pages
Java Exceptions (try...catch) Tutorial
❮ Errors & Exceptions