5

I have many test cases written in C# using Selenium2 Webdriver with NUnit. I have a problem that when a NoSuchElementException is thrown, it is treated as an unhandled exception despite me using a catch block.

An example:

try
   {
       element = driver.FindElement(By.Id("ELEMENT_ID"));
   }
catch (NoSuchElementException)
   {
       // Handle exception...                    
   }

I don't understand why this is giving me the error "NoSucElementException was unhandled by user code." I must be doing something wrong but I can't see what...

5

How Selenium determines whether an element exists and how it behaves when an element is not found seems to vary from one release to the next. With the current release, it is possible to finesse the problem by switching to the findElements method. For example, in Java I would do something like this:

elements = driver.findElements(By.id(Element_ID"));
if (elements.empty()) {
   // element not found -- react accordingly
}
  • Agree completely, this is the way (or minor variations on this way) it should done. – Ardesco Mar 23 '12 at 21:45
  • 1
    I tried this and it worked to avoid the exception. I'm still curious as to why the NoSuchElementException isn't caught by my code above - perhaps a problem with the NoSuchElementException class itself? But it's much better to avoid the exception being thrown at all, so thanks for the solution :) – SteveCZ Mar 26 '12 at 8:36
1

Please check your imports.Check your console if its throwing exception from same package that you have imported? There are two packages 1.java.util.NoSuchElemetFoundException and 2.org.openqa.selenium.NoSuchElemetFoundException.You need to catch the later one

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.