Sobes.tech
Junior — Middle

Explain what an InterruptedException is and in what cases it occurs in Java?

sobes.tech AI

Answer from AI

An InterruptedException in Java occurs when a thread that is in a waiting, sleeping, or blocked state (for example, when calling methods like Thread.sleep(), wait(), join(), or working with blocking queues) is interrupted by another thread using the interrupt() method.

This exception signals that the current thread has been interrupted, and it usually needs to be handled to properly terminate work or perform cleanup. Handling interruptions allows responding to stop or cancel requests.

Example:

try {
    Thread.sleep(10000); // thread sleeps for 10 seconds
} catch (InterruptedException e) {
    // thread was interrupted during sleep
    Thread.currentThread().interrupt(); // restore interrupt status
    System.out.println("Thread was interrupted");
}
Explain what an InterruptedException is and in what… - sobes.tech