我有一些与 C# 和 java 的异常处理 相关的代码。
当出现 StackOverflowException
时 I've read in C# finally block 将不会被执行,因为堆栈上没有空间甚至可以执行任何更多代码,并且当出现 时它也不会被调用ExecutionEngineException
发生,这可能是由对 Environment.FailFast()
的调用引起的。
在我下面的代码 (C#) 中,我有意生成了 StackOverflowException
:
class overflow1
{
public void disp()
{
try
{
Console.WriteLine("disp");
disp();
}
catch(Exception e) {
Console.WriteLine(e);
Console.WriteLine("catch");
}
finally {
Console.WriteLine("finalyyy");
}
}
}
class ExceptionHandling
{
static void Main() {
overflow1 s = new overflow1();
s.disp();
Console.Read();
}
}
输出:
显示
显示
显示
.
.
.
进程因 StackOverFlowException 而终止
正如我所说,如果 StackOverflowException
发生,因为堆栈上没有空间来执行 finally block 的任何更多代码。即使 catch block 的方法也可能由于相同的原因(堆栈中没有更多空间)而未被调用。
现在我已经在 java 中尝试了上面的相同代码:
public class ExceptionHandlingTest {
static int count1 = 0 ,count2=0;
static void disp()
{
try{
System.out.println("disp"+(++count1));
disp();
}catch(StackOverflowError e){
System.out.println(e);
System.out.println("catch");
System.exit(0);
}finally{
System.out.println("handle"+(--count1));
}
}
public static void main(String... args)
{
disp();
}
}
输出:
显示1
显示2
.
.
.
显示2456
句柄2455
句柄2454
.
.
线程“main”中的异常 java.lang.StackOverflowError
.
.
句柄2
句柄1
句柄0
编辑: 事实上,我的问题是代码的行为在两种语言中应该是一样的,因为如果所有堆栈空间都已满,那么在 java JVM 中如何找到更多空间来调用 finally block 的方法?
谢谢。
最佳答案
您的问题出在 Java catch
block 中。 Exception
不是所有可能错误的父类(super class); Throwable
是。 StackOverflowError
扩展了 Error
,而不是 Exception
,因此不会被捕获。最好捕获 StackOverflowError
本身,但也可以捕获 VirtualMachineError
、Error
或 Throwable
。
关于java - 与异常处理相关的查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25997950/