Bird
0
0

Identify the error in this code snippet handling unexpected alerts:

medium📝 Debug Q14 of 15
Selenium Java - Handling Windows, Frames, and Alerts
Identify the error in this code snippet handling unexpected alerts:
try {
  driver.findElement(By.id("save")).click();
} catch (NoAlertPresentException e) {
  driver.switchTo().alert().accept();
}
ANoAlertPresentException should be caught after alert handling
BAlert handling code is inside catch for wrong exception
CAccept() should be replaced with dismiss()
DTry block should include alert handling, not catch
Step-by-Step Solution
Solution:
  1. Step 1: Understand exception usage

    NoAlertPresentException occurs when alert is not present but code tries to switch to alert.
  2. Step 2: Analyze catch block logic

    Alert handling code is wrongly placed inside catch for NoAlertPresentException, which means alert is not present.
  3. Step 3: Correct approach

    Alert handling should be in try block or catch should handle different exception like UnhandledAlertException.
  4. Final Answer:

    Alert handling code is inside catch for wrong exception -> Option B
  5. Quick Check:

    Catch wrong exception for alert handling = error [OK]
Quick Trick: Catch UnhandledAlertException, not NoAlertPresentException for alerts [OK]
Common Mistakes:
  • Catching NoAlertPresentException to handle alert
  • Placing alert.accept() inside catch for missing alert
  • Confusing accept() and dismiss() usage

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Selenium Java Quizzes