1

I know that we should not handle Error in java using try catch, but I tried it for learning and found that we can handle Error similarly Exception using try catch block. Even code after catch block is also getting execute. I generated a StackOverFlowError but still I can initialize local variable. Can any one please explain it?

import java.util.LinkedList;
import java.util.List;

public class ExceptionDemo {

    public static void main(String[] args) {
        try{
              method1();
        }
        catch(Error e){
            System.out.println(e.getStackTrace());

            System.out.println("Hello world");
            int a =10;
            System.out.println(a);          
            method();   
        }       
        System.out.println("Hello world2");
    }

    public static void method1(){
        method1();
    }   

    public static void method(){
        List l1 = new LinkedList();
        l1.add("A");        
        int[] aa = new int[10000];
        aa[0]=25;
        System.out.println(aa[0]);

        int b =10;
        int c = 20;     
        System.out.println( b +""+c);
    }
}

Output of this class is -

 [Ljava.lang.StackTraceElement;@1db9742

Hello world
10
25
1020
Hello world2
Ashok Singh
  • 185
  • 3
  • 11

1 Answers1

5

I focus in my answer on that part of your question that is not related to the "why not catch Errors"; but your implicit idea that you "can't catch Errors". Because: that idea of yours is simply wrong!

You can catch all subclasses of Throwable. Just look at the words: everything that can be thrown can also be caught.

Error is a subclass of Throwable!

But you are correct about the fact that only instances of that other child-class called Exception of Throwable should be caught using try/catch. For "why not catch errors"; that is explained extensively over here!

Community
  • 1
  • 1
GhostCat
  • 127,190
  • 21
  • 146
  • 218
  • 1
    The problem is that if an error has happened, you can't guarantee that the JVM is going to work correctly from that point. Sure, it will let you catch it and try to do some things (after all, it makes sense to log the error) but you should consider your program to be unstable at that point. – D M Feb 09 '17 at 08:10
  • 1
    That is what the last paragraph is pointing to in the end. And just for the record: it really depends: we have a distributed environment, and sometimes, when I put the wrong version of some java class on another system, that causes MethodNotFoundErrors on that systems. And we actually catch those (LinkageErrors methinks) because we know they can happen when we mess up; and catching them allows us to do the required cleanup when our operations fail. – GhostCat Feb 09 '17 at 08:13