简体   繁体   中英

Try/Catch webdriver if is not present in the path

I have the following Selenium code:

System.setProperty("webdriver.chrome.driver", "MYPATH\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get(MYURL);

I was wondering: if I want to use the try/catch Method, is there a specific exception to handle the program if chromedriver.exe is not found in the path?

The only exception that comes to my mind is the basic WebDriverException but I already use it for other purposes.

Setting or getting the property will not throw an exception. It's also related to System not Selenium itself.

Using System.setProperty with chromedriver will set the path to chromedriver, even if it doesn't exist.

Using System.getProperty of a non-existing property will return null.

You can check if the property is set in multiple ways. However, if you want to check if chromedriver.exe exists in the provided path I would do it like this:

String myPath = "src/test/java";
File chromedriverFile = new File(myPath, "chromedriver.exe");
if (!chromedriverFile.exists()) {
    throw new RuntimeException(String.format("chromedriver.exe does not exist in path: %s", myPath));
}

We saved the path to a variable. Then, we created an instance of the File class. The first argument is the path and the second is a file name. Then we check if this file exists or not. If not - throw an unchecked exception.

You can alter the code to do something else if file exists or not.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM