'Cannot catch NoSuchElementException

I've seen quite a few threads on this topic, however I didn't find an answer for my question. I managed to solve my general issue, but I'd like to understand why my first attempts didn't work.

I have a class that is supposed to wait until an element with a specified class appears.

Here's the original code:

void Wait(string className)
{
    var wait = new WebDriverWait(driver, timeout: TimeSpan.FromSeconds(30))
    {
        PollingInterval = TimeSpan.FromSeconds(2)
    };
    wait.IgnoreExceptionTypes(typeof(NoSuchElementException));
    wait.Until(drv => drv.FindElement(By.ClassName(className)));
}

Even though I used wait.IgnoreExceptionTypes(typeof(NoSuchElementException));, the NoSuchElementException exception is being thrown anyway on the line wait.Until(drv => drv.FindElement(By.ClassName(className)));.

My second attempt was this:

void Wait(string className)
{
    var wait = new WebDriverWait(driver, timeout: TimeSpan.FromSeconds(30))
    {
        PollingInterval = TimeSpan.FromSeconds(2)
    };
    wait.IgnoreExceptionTypes(typeof(NoSuchElementException));
    
    try
    {
        wait.Until(drv => drv.FindElement(By.ClassName(className)));
    }
    catch(NoSuchElementException) {}
}

Again, the same line throws the exception, even though it's inside of try-catch. Here's a screenshot:

enter image description here

My final code looks as follows and it works:

void Wait(string className)
{
    var wait = new WebDriverWait(driver, timeout: TimeSpan.FromSeconds(30))
    {
        PollingInterval = TimeSpan.FromSeconds(2)
    };
    wait.IgnoreExceptionTypes(typeof(NoSuchElementException));
    
    wait.Until(drv =>
    {
        try
        {
            return drv.FindElement(By.ClassName(className));
        }
        catch(NoSuchElementException) { }

        return null;
    });
}

I'm catching an exception inside of the lambda function.

The things that I don't understand:

  1. In the first approach, why the IgnoreExceptionTypes method doesn't work?
  2. In the second approach, why isn't the exception caught? Doens't it "bubble up" from lambda where it's originally thrown?


Solution 1:[1]

Instead of catching NoSuchElementException try catching explicitly OpenQA.Selenium.NoSuchElementException since there are more than one NoSuchElementException exception in C# (and in Java)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Prophet