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

标签 java exception recursion null try-catch

演示递归及其占用堆栈空间的缺点。我写了下面的代码。我发现当 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/

相关文章:

java - JAX-RS 请求拦截器缺少依赖项

java - 在 Java 中实现异常的问题

java - 将异常记录到数据库中

c - 使用递归用最少的硬币进行找零

java - 如何从时间(小时)中删除前导零

java - 列出文件夹中的所有文件以及子文件夹

java - 使用解析的 url 改造 Get 方法

spring-boot - 抛出异常Spring Boot Webflux

python - 如何迭代或递归确定二维数组中的邻居?

python - 如何根据在 Python 中保持顺序的一个 bool 字段创建元组列表的所有排列