You may try this:
public void ClickButton () throws InterruptedException
{
WebElement button = driver.findElement(By.id("button"));
String Source = driver.getPageSource();
if (Source.contains(button))
{
button.click();
Thread.sleep(3000);
}
else
{
driver.quit;
}
}
Hope this can be helpful. Let me know if you are still facing problem.
solved Using IF commands to Check if a button exists in Selenium Java [closed]