What is InterruptedException? Why do we need to catch it when calling Thread.sleep()?

Alex Chaffee

InterruptedException is thrown if another thread calls interrupt() on the sleeping thread while it is asleep. If sleep() is setting an alarm clock before bed, interrupt() is a midnight phone call.

This means that you can safely ignore the exception (with catch (InterruptedException e) {}) since in general, only code that you write will ever call interrupt. Since you didn't write it, you know it won't happen. :-)

InterruptedException was not implemented in Java 1.0; however, it is definitely available now.

The exception will also get thrown if the "interrupted" flag is set in the thread, which happens if another thread calls interrupt even before the original thread sleeps.

See also Is it possible to interrupt a running thread? for interesting details.

0 Comments  (click to add your comment)
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

About | Sitemap | Contact