10

The perfect StackOverflow question has finally come....

How do I catch a StackOverflow exception!

It seems in .NET Core the StackOverflowException isn't available:

enter image description here

And if I run this code:

using System;

namespace PlayGround.Core.Console
{
    public class Program
    {
        public static void Main(string[] args)
        {
            try
            {
                DoSomething();
            }
            catch(Exception e)
            {
                System.Console.WriteLine("Bugger");
            }

        }

        private static void DoSomething()
        {
            DoSomething();
        }
    }
}

I get this:

enter image description here

You can see my exception handler didn't run. So how do I go about catching this exception in .NET Core?

EDIT September 15th, 2017: In .NET Core 2.0 there is now a StackOverflowException class, but it still doesn't actually catch a stackoverflow exception.

joshcomley
  • 28,099
  • 24
  • 107
  • 147
  • See [http://stackoverflow.com/questions/1599219/c-sharp-catch-a-stack-overflow-exception/1599238#1599238](http://stackoverflow.com/questions/1599219/c-sharp-catch-a-stack-overflow-exception/1599238#1599238) for a discussion of why it is not catchable – John Davidson Sep 15 '16 at 13:52
  • Possible duplicate of [StackOverflowException in .NET](http://stackoverflow.com/questions/107735/stackoverflowexception-in-net) – Technetium Sep 15 '16 at 19:52
  • 1
    @Technetium, not a duplicate because in .NET it is possible to catch these exceptions and the class itself is accessible to use in a try/catch. .NET Core is a different animal all together. – joshcomley Sep 19 '16 at 13:52
  • Indeed, you are correct @joshcomley. This is strange. You can see it in the source code next to everything else under `System`. https://github.com/dotnet/corefx/blob/master/src/mscorlib/ref/Compat/mscorlib.cs – Technetium Sep 19 '16 at 15:25
  • Yep, it's also strange that the exception itself throws *as* a StackOverflowException, but it seems it is platform dependent and as such has somehow been obfuscated away – joshcomley Sep 22 '16 at 13:03
  • See if you can dig the answer from https://github.com/dotnet/coreclr/search?p=1&q=stackoverflowexception&type=Issues&utf8=✓ If not, post this question there to see how Microsoft guys respond. – Lex Li Sep 15 '17 at 04:00
  • 1
    @LexLi good idea, have now done so: https://github.com/dotnet/coreclr/issues/14010 – joshcomley Sep 15 '17 at 12:29

1 Answers1

2

Since CLR 2.0 you cant catch a StackOverflowException. Unless you were the one to throw it it.

https://blogs.msdn.microsoft.com/jaredpar/2008/10/22/when-can-you-catch-a-stackoverflowexception/

Zoxive
  • 116
  • 2
  • 4