Bird
0
0

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?
Atry { driver.findElement(By.id("btn")).click(); } catch (UnhandledAlertException e) { driver.switchTo().alert().accept(); driver.findElement(By.id("btn")).click(); }
Bdriver.findElement(By.id("btn")).click(); driver.switchTo().alert().accept();
Cdriver.switchTo().alert().accept(); driver.findElement(By.id("btn")).click();
Dtry { driver.switchTo().alert().accept(); } catch (NoAlertPresentException e) { driver.findElement(By.id("btn")).click(); }
Step-by-Step Solution
Solution:
  1. Step 1: Understand unexpected alert during click

    Clicking the button may cause an unexpected alert, throwing UnhandledAlertException.
  2. Step 2: Use try-catch to handle alert and retry click

    Catch UnhandledAlertException, accept alert, then retry clicking the button to ensure action completes.
  3. 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.
  4. Final Answer:

    try { driver.findElement(By.id("btn")).click(); } catch (UnhandledAlertException e) { driver.switchTo().alert().accept(); driver.findElement(By.id("btn")).click(); } -> Option A
  5. Quick Check:

    Catch alert exception, accept, retry click = safe handling [OK]
Quick Trick: Catch alert exception, accept alert, then retry action [OK]
Common Mistakes:
MISTAKES
  • Not retrying click after alert acceptance
  • Handling alert before click without exception
  • Catching wrong exception types

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Selenium Java Quizzes