I get exception when using Thread.sleep(x) or wait()

vincent low picture vincent low · Jul 27, 2010 · Viewed 887.4k times · Source

I have tried to delay - or put to sleep - my Java program, but an error occurs.

I'm unable to use Thread.sleep(x) or wait(). The same error message appears:

unreported exception java.lang.InterruptedException; must be caught or declared to be thrown.

Is there any step required before using the Thread.sleep() or wait() methods?

Answer

Konrad Garus picture Konrad Garus · Jul 27, 2010

You have a lot of reading ahead of you. From compiler errors through exception handling, threading and thread interruptions. But this will do what you want:

try {
    Thread.sleep(1000);                 //1000 milliseconds is one second.
} catch(InterruptedException ex) {
    Thread.currentThread().interrupt();
}