Reputation: 19225
I got the following exception while executing my software:
Exception in thread "main" java.lang.IllegalArgumentException: Delay must be to 0 to 60,000ms
at java.awt.Robot.checkDelayArgument(Robot.java:544)
at java.awt.Robot.delay(Robot.java:534)
at com.company.Main.main(Main.java:10)
It surprises me that there is a sleeping time limit and that the standard library exception message has bad grammar/a typo (to 0 to
?). After checking the source code of the delay()
method, I noticed that it restricts the waiting time as the exception stated:
/**
* Sleeps for the specified time.
* To catch any <code>InterruptedException</code>s that occur,
* <code>Thread.sleep()</code> may be used instead.
* @param ms time to sleep in milliseconds
* @throws IllegalArgumentException if <code>ms</code> is not between 0 and 60,000 milliseconds inclusive
* @see java.lang.Thread#sleep
*/
public synchronized void delay(int ms) {
checkDelayArgument(ms);
try {
Thread.sleep(ms);
} catch(InterruptedException ite) {
ite.printStackTrace();
}
}
private static final int MAX_DELAY = 60000;
private void checkDelayArgument(int ms) {
if (ms < 0 || ms > MAX_DELAY) {
throw new IllegalArgumentException("Delay must be to 0 to 60,000ms");
}
}
Why is this being done? It seems like poor API design. Which purpose does it have besides catching the redundant InterruptedException
checked exception for you and synchronizes the call?
Upvotes: 6
Views: 548
Reputation: 44230
No one can answer that apart from the original developer(s).
You can quite clearly see that all it does is call Thread::sleep
, so just do the same thing. You don't need to call Robot::delay
.
The following is precisely equivalent, without the arbitrary restriction
Robot r;
long sleepDuration = 60001;
synchronized (r) {
try {
Thread.sleep(sleepDuration);
} catch(InterruptedException ite) {
ite.printStackTrace();
}
}
It seems like poor API design
This class is 19 years old. There's plenty of bad design decisions in the JDK, especially in the older stuff.
Upvotes: 2