Kliver Max
Kliver Max

Reputation: 5299

How to handle StackOverflowException

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?

Upvotes: 0

Views: 584

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1504182

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.

Upvotes: 5

Related Questions