Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET Core - how to catch a StackOverflowException

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.

like image 700
joshcomley Avatar asked Sep 14 '16 17:09

joshcomley


People also ask

Can I catch StackOverflowException C#?

Starting with the . NET Framework version 2.0, a StackOverflowException object cannot be caught by a try-catch block and the corresponding process is terminated by default. Consequently, users are advised to write their code to detect and prevent a stack overflow.

How do I get StackOverflowException?

StackOverflowExceptions to be caught in the typical try-catch block. Instead, the process terminates itself by default. Execution will break if a System. StackOverflowException occurs during debugging within Visual Studio, for example.

Can we handle StackOverflowException?

Applying the HandleProcessCorruptedStateExceptionsAttribute attribute to a method that throws a StackOverflowException has no effect. You still cannot handle the exception from user code.

Can you catch a StackOverflowException Java?

StackOverflowError is an error which Java doesn't allow to catch, for instance, stack running out of space, as it's one of the most common runtime errors one can encounter.


1 Answers

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/

like image 83
Zoxive Avatar answered Oct 22 '22 17:10

Zoxive