Search code examples
c#try-catchstack-overflow

C# catch a stack overflow exception


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(...)


Solution

  • 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"