How To Resolve UnhandledAlertException While working with Alert Box in WebDriver in Selenium

Share and Enjoy !

Many a times, while testing web application, we face such situation where we need to handle javascript alert from our webdriver code in selenium.

And it is also very common that we get the below written UnhandledAlertException   while running our code.

The code may look like-

:org.openqa.selenium.UnhandledAlertException: Modal dialog present: The account has been modified, discard changes?
Build info: version: ‘2.39.0’, revision: ‘ff23eac’, time: ‘2013-12-16 16:12:12’
System info: host: ‘HOST-ABCD’, ip: ‘, ‘Windows Server 2008 R2’, os.arch: ‘amd64’, os.version: ‘6.1’, java.version: ‘1.7.0_51’
Session ID: ad3746bf-4c03-4de9-9bb8-17831538c562
Driver info:
Capabilities [{platform=WINDOWS, javascriptEnabled=true, elementScrollBehavior=0, ignoreZoomSetting=false, enablePersistentHover=true, ie.ensureCleanSession=false, browserName=internet explorer, enableElementCacheCleanup=true, unexpectedAlertBehaviour=dismiss, version=8, ie.usePerProcessProxy=false, cssSelectorsEnabled=true, ignoreProtectedModeSettings=false, requireWindowFocus=false, handlesAlerts=true, initialBrowserUrl=http://localhost:9493/, ie.forceCreateProcessApi=false, nativeEvents=true, browserAttachTimeout=0, ie.browserCommandLineSwitches=, takesScreenshot=true}]

The code we use to combat the alert box is given below:


Let us understand why this exception comes then:
It is seen many a time the application is slow in nature and selenium is trying to execute the code before the alert pop up. So the next statement will have this exception. Many coder try to put a Thread.Sleep(5) before the above code. But the success rate to avoid this exception is upto the speed of application.

So how to resolve this issue?

Well instead of Thread.Sleep(5) use a more correct method..

WebDriverWait wait =new WebDriverWait(driver, 15);

So this code will wait for the alert to come and then it will click on ok what accept button.

Problem might solve, but is this the correct solution??

See also  Issues with Sendkeys Not Working With Different Browser

Probably, No!!!.
This condition does not hold good for the case where the pop up do not appear. It will go to infinite loop. Let us make it little safe:

public boolean isAlertPresent(){
return true;
catch(Exception e){
return false;



There is one more beautiful way to solve this issue:

for(String s: webDriver.getWindowHandles()){
//see if alert exists here.

Share and Enjoy !

One thought on “How To Resolve UnhandledAlertException While working with Alert Box in WebDriver in Selenium

Leave a Reply

Your email address will not be published. Required fields are marked *