2012-07-27 169 views
1

内的几秒钟后,将下面的程序输出抛出异常匿名递归函数

过程由于终止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"); 
      } 


     } 
    } 
} 
+1

附注:在“Factorial”中捕捉和重掷的点是什么? (忽略你无法捕获StackOverflowException的事实) – 2012-07-27 20:15:55

+0

[C#捕获堆栈溢出异常]的可能重复(http://stackoverflow.com/questions/1599219/c-sharp-catch-a-stack-overflow-exception ) – 2012-07-27 20:16:58

+0

@BrianRasmussen此源代码应该不言自明;我想检查BigInteger可以包含的最大因子。 – 0x6B6F77616C74 2012-07-27 20:23:40

回答

1

从MSDN:

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

所以你不能再捕捉到这个例外。