爲了演示遞歸及其使用堆棧空間的缺點。我寫了下面的代碼。當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
}
}
不知道StakOverflowError是否有消息。而且,catch子句中的println很可能會導致另一個StackOverflowError。 – Henry
@亨利爲什麼?如果正在執行catch塊,則意味着已經完成了try塊,並且該函數已完成(已成功或未完成)並且已關閉堆棧。 –
@亨利,就像現在堆棧空間被吹起一樣。 – ComputationalPhysicist