Search code examples
c#selenium-webdrivertestingappium

Catch ElementClickInterceptedException in Selenium with C#


I'm trying to catch a ElementClickInterceptedException in C#, but it apppears I'm doing something wrong since it doesn't go to the catch code line when I get that exception while debugging. Strange thing is that if the test runs normally, it doesn't throw the exception at that point, but when it runs in debug mode, it does...enter image description here

I try catching the exception because Selenium keeps throwing it and I don't know what to do to solve it.


Solution

  • Seems like I have been catching the wrong exception all along. Anyway, I'll leave the code that worked for me when I got a TargetInvocationException or ElementClickInterceptedException so anyone facing the same issue can solve it like I did:

    public bool clickBtn(IWebElement btnElement)
            {
                bool result = false;
                int attempts = 0;
                while (attempts < 10)
                {
                    try
                    {
                        waitForClickable(btnElement);
                        btnElement.Click();
                        result = true;
                        break;
                    }
                    catch (TargetInvocationException e)
                    {
                    }
                    catch (StaleElementReferenceException e)
                    {
                    }
                    attempts++;
                    Thread.Sleep(2000);
                }
                return result;
            }
    

    I think you can get rid of the second catch and it will work all the same :)

    Also, I leave the code for the "waitForClickable" method:

    internal void waitForClickable(IWebElement button)
            {
                try
                {
                    wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementToBeClickable(button));
                }
                catch (NoSuchElementException e)
                {
                    throw new NoSuchElementException("It wasn't possible to click the element.\n" + e);
                }
            }