0

Here Is my program that produces an InterruptedException.

timepass.java

 public class timePass {
    private static void book() {
        System.out.print("book");
    }
    public static void main(String args[]){
            Thread.sleep(1);
            book();
      }
    }

I would like to know the reason for the thrown exception.

VVN
  • 1,607
  • 2
  • 16
  • 25
faizal vasaya
  • 517
  • 3
  • 12

3 Answers3

1

put code in try catch block

 try
  {
  Thread.sleep(1);
  book();
  } 
  catch(InterruptedException e)
  {
   System.out.println("Error message");
  }
sasikumar
  • 12,540
  • 3
  • 28
  • 48
  • Yes , I understand this can be a solution for my problem. But I would like to know the reason why this exception is being thrown. – faizal vasaya Mar 09 '16 at 06:28
  • read this http://stackoverflow.com/questions/1087475/when-does-javas-thread-sleep-throw-interruptedexception – sasikumar Mar 09 '16 at 06:30
1

It's because Thread.sleep could probably throw an Exception so you just have to catch it or give it to a higher level.

public static void main(String args[]) throws Exception {
    Thread.sleep(1);
    book();
}
Kordi
  • 2,405
  • 1
  • 14
  • 13
0

When you use thread sleep you need to try catch a (InterruptedException e)

ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97