The StackOverflowException

Take a look at the following code:

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


    static void 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:


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

Published by Colin Mackay

I blog at I also talk at software development conferences.

Join the Conversation

1 Comment

  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 comment

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

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

Google photo

You are commenting using your Google 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 )

Connecting to %s

<span>%d</span> bloggers like this: