Handling InterruptedException with try-catch
What you'll learn: How to properly catch and respond to InterruptedException when a sleeping thread is interrupted.
Since InterruptedException is a checked exception, any code that calls Thread.sleep() must handle it. The most common pattern is wrapping the sleep call in a try-catch block.
The Standard Pattern
When you call Thread.sleep(), you must catch InterruptedException:
try {
Thread.sleep(2000); // Sleep for 2 seconds
} catch (InterruptedException e) {
// Handle the interruption
System.out.println("Thread was interrupted during sleep");
}
What Should You Do in the Catch Block?
There are several valid approaches depending on your use case:
1. Log and continue (if the interruption isn't critical):
catch (InterruptedException e) {
System.out.println("Sleep interrupted, but continuing");
}
2. Restore the interrupt status (best practice for library code):
catch (InterruptedException e) {
Thread.currentThread().interrupt(); // Restore interrupt flag
}
3. Exit the thread gracefully:
catch (InterruptedException e) {
System.out.println("Thread interrupted, exiting");
return; // Exit the run method
}
Why This Matters
Think of interruption like a fire alarm in a building—when it sounds, you need a plan. Ignoring it (empty catch block) is dangerous. Acknowledging it and deciding whether to evacuate or investigate is responsible handling.
The Thread.currentThread().interrupt() pattern is especially important because it preserves the interruption signal for code higher up the call stack that might need to know the thread was interrupted.
Key Takeaway: Always wrap Thread.sleep() in try-catch for InterruptedException, and in the catch block, either restore the interrupt status with Thread.currentThread().interrupt() or take appropriate cleanup action—never silently ignore it.