Jok*_*ker 1 java stack-overflow error-handling
据我了解,以下代码应打印0为输出,因为堆栈已满,应该立即退出方法。
但是,当我运行以下代码时,它100在第一种情况下打印1,而在第二种情况下打印:
class ErrorAndException {
public static int callStackOverflow() {
try {
callStackOverflow();
return 100;
} catch (Error e) {
System.out.println(e);
return 0;
} finally {
}
}
public static void main(String[] args) {
System.out.println(callStackOverflow());
}
}
Run Code Online (Sandbox Code Playgroud)
案例-2
class ErrorAndException {
public static int callStackOverflow() {
try {
callStackOverflow();
return 100;
} catch (Error e) {
System.out.println(e);
return 0;
} finally {
return 1
}
}
public static void main(String[] args) {
System.out.println(callStackOverflow());
}
}
Run Code Online (Sandbox Code Playgroud)
请帮助我了解这种行为。
只有对的最终调用callStackOverflow()(StackOverflowError抛出该调用)才返回0。但是,当它返回时,先前对callStackOverflow()all的调用将返回100。您的main方法仅输出初始调用所返回的值callStackOverflow(),即100。
如果您希望将方法0返回给main方法,callStackOverflow()则必须返回递归调用返回的值:
public static int callStackOverflow() {
try {
return callStackOverflow();
} catch (Error e) {
System.out.println(e);
return 0;
} finally {
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
53 次 |
| 最近记录: |