-3

Why is a try/catch exception handling statement required in Java for the below line:

TimeUnit.MILLISECONDS.sleep(250);

I just want my code to sleep for 250 milliseconds before executing the next line. Why is a try-catch statement required? I can’t forsee any exceptions with this. The sleep function in python doesn't require a try catch.

The exception I get in the IDE without adding the try catch is:

Error:(124, 40) error: unreported exception InterruptedException; must be caught or declared to be thrown

When I surround it in the try catch as per below it works fine:

    try {
        TimeUnit.MILLISECONDS.sleep(250);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
codepurveyor
  • 43
  • 1
  • 8

2 Answers2

0

You need to catch the exception simply because the thread running (sleeping) might be interrupted and you need to catch the interruption.

From the Oracle description of the InterruptedException

Thrown when a thread is waiting, sleeping, or otherwise occupied, and the thread is interrupted, either before or during the activity.

Akhadra
  • 419
  • 3
  • 10
0

Interrupting a thread that is sleeping is a very important part of Java. It provides control when you need to stop an application (or a process) and do not want to be halted from doing so due a thread sleeping. The InterruptException allows developers to catch interrupt attempts and deal with it.

Maybe your beef is with checked exceptions in general.... which is a feature of Java that many people do not like. We can understand your frustration with checked exceptions. You can read up more on checked exceptions in Java via Google.

Jose Martinez
  • 11,452
  • 7
  • 53
  • 68