Take the 2-minute tour ×
Software Quality Assurance & Testing Stack Exchange is a question and answer site for software quality control experts, automation engineers, and software testers. It's 100% free, no registration required.

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...

share|improve this question

2 Answers 2

up vote 4 down vote accepted

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
}
share|improve this answer
    
Agree completely, this is the way (or minor variations on this way) it should done. –  Ardesco Mar 23 '12 at 21:45
    
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

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

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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