You want to write a Selenium Java method that safely clicks a button even if an unexpected alert appears. Which code snippet correctly handles this scenario?
hard📝 Application Q15 of 15
Selenium Java - Handling Windows, Frames, and Alerts
You want to write a Selenium Java method that safely clicks a button even if an unexpected alert appears. Which code snippet correctly handles this scenario?
Clicking the button may cause an unexpected alert, throwing UnhandledAlertException.
Step 2: Use try-catch to handle alert and retry click
Catch UnhandledAlertException, accept alert, then retry clicking the button to ensure action completes.
Step 3: Verify other options
driver.findElement(By.id("btn")).click();
driver.switchTo().alert().accept(); and C do not handle exceptions; try {
driver.switchTo().alert().accept();
} catch (NoAlertPresentException e) {
driver.findElement(By.id("btn")).click();
} tries alert first which may not exist before click.