一、timeoutException是什麼
TimeoutException是Java中的一個異常類,當程序的某個方法 ran out of time 而不能夠完成它的任務的時候,就會拋出這個超時異常。
簡單來說,當程序執行的時間超過了程序預先設置的時間限制,就會拋出TimeoutException異常。
二、timeoutException的用法
TimeoutException一般會配合一些帶有時間限制的操作使用,例如Thread.sleep()方法、Future.get()方法等。
例如,在使用Future.get()方法時,如果設定了超時時間,而程序無法在規定的時間內完成任務,就會拋出TimeoutException異常。代碼示例如下:
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
public class TimeoutExceptionDemo {
public static void main(String[] args) throws Exception {
ExecutorService executorService = Executors.newSingleThreadExecutor();
Future<String> future = executorService.submit(() -> {
Thread.sleep(1000);
return "Hello World!";
});
try {
String result = future.get(500, TimeUnit.MILLISECONDS);
System.out.println(result);
} catch (TimeoutException e) {
System.err.println("Task timed out!");
}
executorService.shutdown();
}
}
上述代碼表示,在使用ExecutorService.submit()方法提交任務時,設置了超時時間為500毫秒,若任務未能在500毫秒內完成,則拋出TimeoutException異常,輸出”Task timed out!”。
三、腳本報錯timeoutException
在編寫腳本時,有時會遇到timeoutException的錯誤,此時一般是程序無法在規定的時間內完成任務,需要進行一些優化。下面介紹三種可能的情況:
1、網絡連接超時
在進行網絡請求時,可能會發生網絡連接超時的情況,此時需要設置合理的超時時間或者進行重試操作。代碼示例如下:
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.SocketTimeoutException;
import java.net.URL;
public class ConnectionTimeoutDemo {
public static void main(String[] args) {
try {
HttpURLConnection connection = (HttpURLConnection) new URL("http://www.baidu.com").openConnection();
//設置超時時間為5秒
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
int responseCode = connection.getResponseCode();
System.out.println("Response code: " + responseCode);
connection.disconnect();
} catch (SocketTimeoutException e) {
System.err.println("Connection timed out!");
} catch (IOException e) {
e.printStackTrace();
}
}
}
上述代碼表示,在進行網絡請求時,設置了超時時間為5秒,若在5秒內無法完成請求,則拋出SocketTimeoutException異常,輸出”Connection timed out!”。
2、瀏覽器請求超時
在使用Selenium等自動化測試工具進行Web UI自動化測試時,可能會遇到超時的情況,此時需要進行一些優化。下面是一段Selenium代碼示例:
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class TimeoutExceptionDemo {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
try {
//打開網頁
driver.get("http://www.baidu.com");
//等待搜索框元素出現,最多等待5秒
WebDriverWait wait = new WebDriverWait(driver, 5);
wait.until(ExpectedConditions.presenceOfElementLocated(By.id("kw")));
//輸入搜索關鍵詞
driver.findElement(By.id("kw")).sendKeys("Hello World!");
//點擊搜索按鈕
driver.findElement(By.id("su")).click();
//等待搜索結果元素出現,最多等待5秒
wait.until(ExpectedConditions.presenceOfElementLocated(By.id("content_left")));
} catch (TimeoutException e) {
System.err.println("Timeout exception!");
}
driver.quit();
}
}
上述代碼表示,在使用WebDriver進行瀏覽器操作時,等待元素出現的最長時間為5秒,若元素在5秒內未能出現,則拋出TimeoutException異常,輸出”Timeout exception!”。
3、程序循環超時
在程序進行循環操作時,可能會遇到超時的情況,此時需要使用計時器進行優化。代碼示例如下:
import java.util.Timer;
import java.util.TimerTask;
public class TimeoutExceptionDemo {
public static void main(String[] args) {
Timer timer = new Timer();
//在5秒後執行任務
timer.schedule(new TimerTask() {
@Override
public void run() {
System.out.println("Task completed!");
}
}, 5000);
//等待任務完成或超時
while (true) {
if (timer.purge() > 0) {
timer.cancel();
break;
}
}
}
}
上述代碼表示,在使用Timer進行計時時,若任務在5秒內未能完成,則取消任務並拋出TimeoutException異常。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/201145.html
微信掃一掃
支付寶掃一掃