2016-07-04 39 views
2

爲了演示遞歸及其使用堆棧空間的缺點。我寫了下面的代碼。當N非常大時(例如100000),我發現它返回了預期的錯誤(「java.lang.StackOverflowError」)。然後我嘗試使用下面給出的類和後續的驅動程序類來捕獲此特定錯誤。然而NetBeans IDE中返回「空」如下圖所示的結果:捕捉「堆棧溢出」錯誤返回「空」

Caught stack Overflow error: null

The factorial of log of 100000 is 68687.75095683799

Direct calculation 1051299.221899134

BUILD SUCCESSFUL (total time: 0 seconds)

有沒有辦法返回實際的錯誤?有人能幫我解決我做錯了什麼嗎?

package recursiondemo; 

import static java.lang.Math.log; 

/** This class demonstrates the recursion with calculation of the value log(N!) 
* log(N!) = log(N*(N-1).....3*2*1) = log(N) + log (N-1) + ......log(3) + log (2) + log(1) 
* @author = 
*/ 
public class logRecursion implements recursionInterface { 
    //private int localCounter = 0; 

    public logRecursion(){ 

    } 

    /** 
    * 
    * @param localCounter 
    * @return 
    */ 
    //@Override 
    public double directCalculation(int localCounter){ 
     double result = 0.0; 
     int loopCounter = localCounter; 

     while (loopCounter >=1) { 
      result += log(loopCounter); 
      --loopCounter; 
     } 
     return result; 
    } 

    public double calculation(int localCounter) throws Exception{ 

     if (localCounter == 1) { 
      return 0.0; 
     } 

     if (localCounter <= 0) { 
      throw new Exception("Factorials are not defined for the input given"); 
     } 
     try { 
      return log(localCounter) + calculation(localCounter - 1); // Recursion 
     } 
     catch (StackOverflowError e) { 
     System.err.println("Caught stack Overflow error: " + e.getMessage()); 
     } 
     return 0.0; // This is an arbitrary return value to avoid compile time error of no return parameter. So this return value is meaning less 
    } 

} 

package recursiondemo; 

/** 
* Driver class 
* @author 
*/ 
public class RecursionDemo { 

    /** 
    * @param args the command line arguments 
    * @throws java.lang.Exception 
    */ 
    public static void main(String[] args) throws Exception { 
     // TODO code application logic here 
     logRecursion test; 
     test = new logRecursion(); 
     System.out.println("The factorial of log of " + args[0] + " is " + test.calculation(Integer.parseInt(args[0]))); // Recursion 
     System.out.println("Direct calculation " + test.directCalculation(Integer.parseInt(args[0]))); // Direct calculation 
    } 

} 
+1

不知道StakOverflowError是否有消息。而且,catch子句中的println很可能會導致另一個StackOverflowError。 – Henry

+0

@亨利爲什麼?如果正在執行catch塊,則意味着已經完成了try塊,並且該函數已完成(已成功或未完成)並且已關閉堆棧。 –

+0

@亨利,就像現在堆棧空間被吹起一樣。 – ComputationalPhysicist

回答

2

StackOverflowError沒有消息(通常是由運行時環境拋出的異常的情況下)。這就是爲什麼你的日誌聲明打印null。請注意,這不是您通常想要捕捉的異常/錯誤。

無論如何,如果你想記錄一個更有意義的信息到控制檯,只需使用錯誤的toString()方法,該方法將返回它的類名(+的詳細消息,如果有的話):

System.err.println("Caught stack Overflow error: " + e); 
+0

謝謝。試了一下,並返回了預期的異常。 – ComputationalPhysicist