What does Thread.sleep() do, and why does it need try/catch?

September 19, 2026 3 answers
Asked by thermal.expansion
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?

Answers

6hz_tremolo
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.

2 dozen plums: Also, the sample loop needs to change counter somewhere, such as counter++, or it will keep running forever if counter starts at 0.

Reply to this answer
linguistics_student
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.

2Softbound: 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.

Reply to this answer
mix ratio 4to1
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.

please define terms: The thread can also wake early if another thread interrupts it. Thatโ€™s why sleep declares InterruptedException.

Reply to this answer

Add your answer

Answers are reviewed before publication.

Related Discussions