在递归函数中抛出一个匿名异常

时间:2012-07-27 20:09:54

标签: c# exception recursion

几秒钟后,以下程序输出

  

由于StackOverflowException

,进程终止

而不是我的消息。为什么呢?

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");
            }


        }
    }
}

2 个答案:

答案 0 :(得分:2)

在特定情况下,您只能抓住StackOverflowException。因此,永远不会显示您的自定义错误消息。

见这里:C# catch a stack overflow exception
另见:http://msdn.microsoft.com/en-us/library/system.stackoverflowexception.aspx

这很有道理;堆栈溢出表示难以进行的状态(与大多数其他异常类型相比)。

答案 1 :(得分:1)

来自MSDN:

  

从.NET Framework 2.0版开始,try-catch块无法捕获StackOverflowException对象,默认情况下会终止相应的进程。因此,建议用户编写代码以检测并防止堆栈溢出。例如,如果您的应用程序依赖于递归,请使用计数器或状态条件来终止递归循环。

所以你再也无法捕捉到那个例外。