Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to close Selenium WebDriver code without throwing exception on closing it. Java

My main() function contains several sub-functions testing several features / scenarios etc each.
There are several cases of errors that may be found during the test running.
In each of these cases there is no reason to continue running the test so I'm sending a report email and closing the program with driver.close(); or driver.quit(); command.
The browser is closed however the code still trying to run so as the first command in the following sub-function still trying to do things: navigate somewhere, find objects etc but since the browser is already closed Exception is thrown as following:

Exception in thread "main" org.openqa.selenium.remote.UnreachableBrowserException: Error communicating with the remote browser. It may have died.  

or

Exception in thread "main" org.openqa.selenium.remote.SessionNotFoundException: The FirefoxDriver cannot be used after quit() was called.  

So how can I tell my program to stop running and close / quit the browser properly?

like image 801
Prophet Avatar asked Apr 15 '26 22:04

Prophet


2 Answers

Use a try/finally instead of a try/catch.

You don't want to catch the exception and then close the driver, you just want to close the driver at the end of the test, wherever that may be.

And example test method might look like:

public void exampleMethod() {
    WebDriver driver = new FirefoxDriver();

    try {
        //Steps in your test
    }
    finally {
        driver.quit();
    }
}
like image 75
aholt Avatar answered Apr 18 '26 10:04

aholt


Put your driver.quit() inside a try/catch block.

like image 25
Vikas Ojha Avatar answered Apr 18 '26 12:04

Vikas Ojha



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!