Software Development

The StackOverflowException

Take a look at the following code:

class Program
{
    static void Main(string[] args)
    {
        try
        {
            RecurseForever();
        }
        catch (StackOverflowException)
        {
            Console.WriteLine("Caught Stack Overflow Exception");
        }
        catch (Exception)
        {
            Console.WriteLine("Caught general Exception");
        }

        Console.ReadLine();
    }

    static void RecurseForever()
    {
        RecurseForever();
    }
}

What do you think the output of the program will be?

If you had asked me a few days ago I’d have said the output would be “Caught Stack Overflow Exception”, however that isn’t the case. If you run the code in the debugger this is what you actually get:

StackOverflowException

The exception simply isn’t caught.

If the application isn’t being debugged it will simply end at this point. It goes directly to jail. It does not pass GO. It does not collect £200.

ConsoleApplication2 has stopped working

One thought on “The StackOverflowException

  1. Yup, that’s written in the documentation. Following is what MSDN is saying,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.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s