我在執行軟件時遇到以下異常: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)令我驚訝的是,有一個睡眠時間限制,并且標準庫異常消息有錯誤的語法/拼寫錯誤(to 0 to?)。檢查該方法的源代碼后delay(),我注意到它限制了等待時間,如異常所述:/** * 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"); }}為什么要這樣做?這似乎是糟糕的 API 設計。InterruptedException除了為你捕獲多余的檢查異常并同步調用之外,它還有什么目的?
1 回答

蕭十郎
TA貢獻1815條經驗 獲得超13個贊
除了原始開發人員之外,沒有人可以回答這個問題。
你可以很清楚地看到它所做的只是 call Thread::sleep,所以只需做同樣的事情即可。你不需要打電話Robot::delay。
以下是完全等價的,沒有任意限制
Robot r;
long sleepDuration = 60001;
synchronized (r) {
? ? try {
? ? ? ? Thread.sleep(sleepDuration);
? ? } catch(InterruptedException ite) {
? ? ? ? ite.printStackTrace();
? ? }
}
API 設計似乎很糟糕
添加回答
舉報
0/150
提交
取消