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:
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.
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.