C# catch a stack overflow exception

Toto picture Toto · Oct 21, 2009 · Viewed 105.3k times · Source

I have a recursive call to a method that throws a stack overflow exception. The first call is surrounded by a try catch block but the exception is not caught.

Does the stack overflow exception behave in a special way? Can I catch/handle the exception properly?

Not sure if relevant, but additional information:

  • the exception is not thrown in the main thread

  • the object where the code is throwing the exception is manually loaded by Assembly.LoadFrom(...).CreateInstance(...)

Answer

JaredPar picture JaredPar · Oct 21, 2009

Starting with 2.0 a StackOverflow Exception can only be caught in the following circumstances.

  1. The CLR is being run in a hosted environment* where the host specifically allows for StackOverflow exceptions to be handled
  2. The stackoverflow exception is thrown by user code and not due to an actual stack overflow situation (Reference)

*"hosted environment" as in "my code hosts CLR and I configure CLR's options" and not "my code runs on shared hosting"