简体   繁体   中英

Query related to Exception handling

I've some piece of code related to Exception Handing for both c# and java.

As I've read in C# that finally block will not be executed when there's a StackOverflowException occurs since there's no room on the stack to even execute any more code and It will also not be called when there's an ExecutionEngineException occurs, which may arise from a call to Environment.FailFast() .

In my below code( C# ) I intentionally generate 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();
        }
    }

Output:

disp

disp

disp

.

.

.

Process is terminated due to StackOverFlowException

As I stated if StackOverflowException occurs since there's no room on the stack to even execute any more code of finally block. Even though catch block's methods also not called perhaps due to the same reason( no more space left into stack).

Now I've tried this above same code in 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();
    }
}

Output :

disp1

disp2

.

.

.

disp2456

handle2455

handle2454

.

.

Exception in thread "main" java.lang.StackOverflowError

.

.

handle2

handle1

handle0

Edit: Indeed my question is that behavior of code should be work same in both the languages because if all stack space filled then how in java JVM found more space to call finally block's methods ?

Thanks.

Your problem is in the Java catch block. Exception is not the superclass for all possible errors; Throwable is. StackOverflowError extends Error , not Exception , so isn't caught. Catching preferably StackOverflowError itself, but also VirtualMachineError , Error or Throwable will work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM