0

I got a huge IEnumerable and when i try to convert it in Array:

var arr = myEnumerable.ToArray();

I got an error:

An unhandled exception of type 'System.StackOverflowException' occurred in System.Core.dll

Same error fired when i do another operations with this collection for example:

var count = myEnumerable.Count();

In Visual Studio i tried to see this collections's properties but when i put mouse coursor on it debug mode end end to work.

I fix this and remove IEnumerable and work with Array only.
But what i don't understand. My code covered by try catch but i can not handle this exception. In meny QA i read that i can't handle StackOverflowException what fired in non user code.

Does it mean that all can do it is just fix error and do not try to catch StackOverflowException?

Kliver Max
  • 5,107
  • 22
  • 95
  • 148
  • 2
    You can't handle that truth. SOE can be raised at any code, it is not necessarily (or likely) that it is the ToArray() call that caused it. Find the recursion bug in your code by single-stepping it with the debugger, paying attention to the call stack. – Hans Passant Jun 09 '18 at 08:16
  • What exactly is your `IEnumerable`? Is it just a `List`? Or is it a custom class, and did you write the enumerator? – John Wu Jun 09 '18 at 08:43
  • Possible duplicate: [C# catch a stack overflow exception](https://stackoverflow.com/q/1599219/3744182). – dbc Jun 09 '18 at 09:27

1 Answers1

5

You don't - a StackOverflowException is a fatal error, basically. You can't catch it; you need to fix your code.

Even if you could catch StackOverflowException, it would still indicate a bug that should be fixed, a bit like NullReferenceException does.

You should look at how your sequence is evaluated. You might get this error if you have a naive tree-walking algorithm using yield return with a recursive call, and a deep tree, for example.

A StackOverflowException almost always involves recursion, and the fix almost always involves either removing recursion entirely, or drastically reducing how much recursion is required.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194