I would probably factor this out into a helper method that did something like the following:
public String clickAndFindPopup(WebDriver driver, By locator) {
// Get the original list of handles to evaluate if a popup
// needs to be handled.
List<String> existingHandles = driver.getWindowHandles();
//Click Search button -- This will cause the pop-up
driver.findElement(locator).click();
Thread.sleep(1000);
List<String> windowHandles = driver.getWindowHandles();
windowHandles.removeAll(existingHandles);
if (windowHandles.size() > 0) {
return windowHandles.get(0);
}
return "";
}
Then you could do something like this:
String popupHandle = clickAndFindPopup(driver, By.id("uw_fc_sub_anc"));
if (!popupHandle.equals("")) {
String currentHandle = driver.getWindowHandle();
driver.switchTo().window(popupHandle);
driver.close();
driver.switchTo().window(currentHandle);
}
The drawback here is that, if you truly only expect the popup on the first iteration, you might dismiss a popup window that you shouldn't be, because you're blindly closing the popup whenever you find one. A much better approach would be to know what state you expect the browser to be in when you're automating it, and asserting on it.