InterruptedException: A Checked Exception
You'll learn why Thread.sleep() forces you to handle InterruptedException and what "checked exception" means in this context.
Why Does Thread.sleep() Throw an Exception?
When you call Thread.sleep(), Java requires you to either catch or declare InterruptedException. This isn't an error in your code—it's Java's way of saying "another thread might want to wake this sleeping thread early."
Think of it like setting an alarm for 8 hours. Normally, you'll wake up when it rings. But someone else (another thread) might shake you awake at 3 AM because there's an emergency. The InterruptedException is that urgent wake-up call.
What "Checked Exception" Means Here
A checked exception is an exception the compiler forces you to handle at compile-time. You must either:
- Catch it with a try-catch block
- Declare it in your method signature with
throws InterruptedException
// Option 1: Catch it
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// Handle interruption
}
// Option 2: Declare it
public void myMethod() throws InterruptedException {
Thread.sleep(2000);
}
This is different from unchecked exceptions (like NullPointerException), which you can handle but aren't required to.
Why Is This Design Important?
Java makes InterruptedException checked because interruption is a cooperative mechanism for thread coordination. The language designers want you to consciously decide how your thread should respond when interrupted—ignore it, clean up resources, or propagate the interruption signal.
Key Takeaway: InterruptedException is a checked exception that Thread.sleep() throws to signal that another thread has interrupted the sleeping thread, and Java forces you to handle it explicitly to ensure robust concurrent code.