StackOverflowError 是嵌套循环太多次导致超出了栈帧深度
public class StackOverFlow {
private static int count = 20000;
private static int base = 1;
public static void main(String[] args) {
cycle();
System.out.println(count);
}
public static void cycle() {
try {
count = count - base;
if (count > base) {
cycle();
}
} catch (Throwable e) {
System.out.println("error is " + e.toString() + count);
}
}
}
运行结果
解决办法
避免嵌套,用循环函数代替嵌套
public class StackOverFlow {
private static int count = 20000;
private static int base = 1;
public static void main(String[] args) {
noCycle();
System.out.println(count);
}
public static void noCycle() {
while (count > base) {
count = count - base;
}
}
}
运行结果