I'm learning Java and trying to understand how Thread.sleep(1000) works in this loop. The code updates a progress bar, pauses for one second, and catches InterruptedException if the thread is interrupted. Why does Java require the try/catch here? What is the difference between handling the exception with try/catch and declaring or throwing it instead? Also, does sleep pause the entire program or only the current thread?
3 Answers
Thread.sleep(1000) pauses the currently running thread for at least about 1,000 milliseconds. It doesn’t necessarily pause the entire application—other threads can continue running. Internally, the runtime asks the operating system to put that thread into a waiting state and wake it later. The delay can be slightly longer because the thread still has to be scheduled again.
InterruptedException is a checked exception in Java, so the compiler requires you to deal with it. A try/catch says, “run this code, and if this particular exception happens, handle it here.” In the example, e.printStackTrace() prints information about the interruption, although production code would usually decide whether to stop, clean up, or restore the interrupt status instead.
The catch block doesn’t make sleep work or make the delay happen. It only defines what your program should do if sleep is interrupted.
Instead of catching the exception, a method can declare it with throws InterruptedException. That passes responsibility to the method’s caller, which must then catch it or declare it again. In simple terms, try/catch means “I’ll handle this here,” while throws means “the caller must handle this.” You generally shouldn’t silently ignore an interruption.
Also, the sample loop needs to change counter somewhere, such as counter++, or it will keep running forever if counter starts at 0.

The thread can also wake early if another thread interrupts it. That’s why sleep declares InterruptedException.