1

After the couple of seconds, the following program outputs

Process is terminated due to StackOverflowException

instead of my message. Why?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Numerics;

namespace maximumVariable
{
    class Program
    {

        public static BigInteger Factorial(int num)
        {
            try
            {
                return (num > 1) ? num*Factorial(num - 1) : (1);
            }
            catch
            {
                throw;
            }
        }


        static void Main(string[] args)
        {
            BigInteger kingKong=0;
            int facParameter=0;
            try
            {

                while (true)
                {
                    kingKong = Factorial(facParameter);
                    facParameter++;
                }

            }
            catch
            {
                Console.WriteLine("The maximum value " + kingKong.ToString()+"has been achieved after "+facParameter.ToString()+" iterations");
            }


        }
    }
}
0x6B6F77616C74
  • 2,559
  • 7
  • 38
  • 65
  • 1
    Side note: What's the point of catching and re-throwing in `Factorial`? (Ignoring the fact that you can't catch StackOverflowException) – Brian Rasmussen Jul 27 '12 at 20:15
  • possible duplicate of [C# catch a stack overflow exception](http://stackoverflow.com/questions/1599219/c-sharp-catch-a-stack-overflow-exception) – Brian Rasmussen Jul 27 '12 at 20:16
  • @BrianRasmussen This source code should be self-explanatory; I wanted to check the maximum factorial that BigInteger can contain. – 0x6B6F77616C74 Jul 27 '12 at 20:23
  • The point is that catching an exception only to immediately re-throw it is redundant. If you're not doing anything with the exception, don't catch it. – Brian Rasmussen Jul 27 '12 at 20:27

2 Answers2

2

You can only catch a StackOverflowException under very specific circumstances. Thus, your custom error message is never displayed.

See here: C# catch a stack overflow exception
See also: http://msdn.microsoft.com/en-us/library/system.stackoverflowexception.aspx

It makes sense; a stack overflow represents a state that is difficult to proceed from (compared to most other exception types).

Community
  • 1
  • 1
Tim M.
  • 53,671
  • 14
  • 120
  • 163
1

From MSDN:

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. For example, if your application depends on recursion, use a counter or a state condition to terminate the recursive loop.

So you can no longer catch that exception.

Servy
  • 202,030
  • 26
  • 332
  • 449
Michael Graczyk
  • 4,905
  • 2
  • 22
  • 34