简体   繁体   中英

C# system.stackoverflow exception

I'm getting a stackoverflow exception on a if/else statement..

Example of code:

if (driver.FindElements(By.XPath("//*[@id='modal']/div/div/div/p[contains(text(), 'Hello World')]")).Count != 0)
{
    Console.WriteLine("Hello World");
}
else
{
    RunOtherFunction();
}

highlighted error code is -

if (driver.FindElements(By.XPath("//*[@id='modal']/div/div/div/p[contains(text(), 'Hello World')]")).Count != 0)

so clearly it's throwing a exception due to not finding the specified element but I have that covered with an else statement?

so I don't understand why it's throwing an exception because if Element isn't found then it should execute " RunOtherFunction(); " instead it's throwing exception?

The highlighted row is correct. It throws exception on the first line and since you don't have a try catch block it won't go into the else.

An Answer based on Java perspective :

I did a small test with the similar usecase where :

  • I opened the url https://www.google.com/
  • Used findElements() to find elements with id as Rs_Sele on the page in a if-else {} loop and used != operator to compare with 0
  • Here is the sample code :

     WebDriver driver = new ChromeDriver(options); driver.get("https://www.google.com/"); if(driver.findElements(By.id("Rs_Sele")).size() !=0) System.out.println("Atleast one element was found"); else System.out.println("No element was found"); 
  • Console Output :

     No element was found 

Analysis

  • The Java Docs of findElements() mentions that this method finds all elements within the current context using the provided mechanism. This method will return as soon as there are more than 0 items in the found collection or will return an empty list if the timeout is reached.
  • So the findElements() method returned an empty list and after the comparision the control went to the else {} block and printed No element was found .
  • The same happened with your code block as well.
  • driver.FindElements(By.XPath("//*[@id='modal']/div/div/div/p[contains(text(), 'Hello World')]")) returned an empty list
  • After the comparision through != operator with 0 else {} block was executed and subsequently RunOtherFunction() function was invoked.

Conclusion

If you are observing stackoverflow exception it is because of the function RunOtherFunction();

References

You can find similar discussions on StackOverflowException in :

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM