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:

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

2 Answers 2


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, 2012 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, 2012 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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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