为什么不建议进行错误处理?

Ash*_*ngh 1 java collections exception-handling data-structures

我知道我们不应该使用try catch来处理java中的Error,但是我尝试了它来学习并发现我们可以使用try catch块处理Error类似的Exception.即使是catch块之后的代码也正在执行.我生成了一个StackOverFlowError,但我仍然可以初始化局部变量.任何人都可以解释一下吗?

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

这门课的成绩是 -

 [Ljava.lang.StackTraceElement;@1db9742

Hello world
10
25
1020
Hello world2
Run Code Online (Sandbox Code Playgroud)

Gho*_*ica 5

我专注于我对你的问题的那部分答案是相关的"为什么抓不住错误"; 但你隐含的想法,你"无法捕捉到错误".因为:你的想法完全错了!

您可以捕获Throwable的所有子类.只要看看这些话:可以抛出的一切也可以被捕获.

错误是Throwable的子类!

但是你应该使用try/catch捕获另一个名为Exception of Throwable的子类的实例,这是正确的.因为"为什么不抓错误"; 这里有广泛的解释!