gpt4 book ai didi

java - 捕获 "stack overflow"错误返回 "Null"

转载 作者:行者123 更新时间:2023-11-30 08:35:28 25 4
gpt4 key购买 nike

演示递归及其耗尽堆栈空间的缺点。我写了下面的代码。我发现当 N 非常大(如 100000)时,它会返回预期的错误(“java.lang.StackOverflowError”)。然后我尝试使用下面给出的类和后续驱动程序类来捕获这个特定错误。但是 Netbeans IDE 返回“null”,如下所示:

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
}

}




最佳答案

您的 StackOverflowError 没有消息(通常是运行时环境抛出的异常)。这就是您的日志语句打印 null 的原因。请注意,这不是您通常想要捕获的异常/错误。

无论如何,如果你想向控制台记录一条更有意义的消息,只需使用错误的 toString() 方法,它将返回它的类名(+ 详细消息,如果有的话):

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

关于java - 捕获 "stack overflow"错误返回 "Null",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38180166/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com