与异常处理相关的查询

Vik*_*rma 1 c# java stack-overflow exception

我有一些部分的相关代码的异常处理两个C#和Java.

正如我在C#读到的那样,当发生这种StackOverflowException情况时,最终块将不会被执行,因为堆栈上没有空间来执行任何更多的代码,并且当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();
        }
    }
Run Code Online (Sandbox Code Playgroud)

输出:

DISP

DISP

DISP

.

.

.

由于StackOverFlowException,进程终止

正如我所说,如果StackOverflowException发生,因为堆栈上没有空间甚至执行finally块的更多代码.即使catch块的方法也未被调用,可能是由于相同的原因(堆栈中没有剩余空间).

现在我在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();
    }
}
Run Code Online (Sandbox Code Playgroud)

输出:

DISP1

DISP2

.

.

.

disp2456

handle2455

handle2454

.

.

线程"main"java.lang.StackOverflowError中的异常

.

.

handle2

句柄1

handle0

编辑: 确实我的问题是代码的行为应该在两种语言中都相同,因为如果所有堆栈空间都填满了,那么java JVM中如何找到更多的空间来调用最终块的方法?

谢谢.

bcs*_*001 5

您的问题出在Java catch块中.Exception不是所有可能错误的超类; Throwable是.StackOverflowError延伸Error,不是Exception,因此没有被抓住.最好捕获StackOverflowError本身,而且VirtualMachineError,Error还是Throwable会工作.