Java的error的捕获

  通常来说,大家都是对Java中的Exception进行捕获和进行相应的处理,有些人说,error就无法捕获了。其实,error也是可以捕获的。Error和Exception都是Throwable的子类。既然可以catch Throwable,那么error也是可以catch的。

下面给个小例子,来验证一下error的捕获。

public class TestCatchError extends Error{
    
    private static final long serialVersionUID = -351488225420878020L;

    public TestCatchError(){
        super();
    }
    
    public TestCatchError(String msg){
        super(msg);
    }
    
    public static void main(String[] args) {
        try {
            throw new TestCatchError("test catch error");
        } catch (Throwable t) {
            System.out.println("step in the catch ~");
            t.printStackTrace();
        }
    }
}

运行结果:

step in the catch ~
TestCatchError: test catch error
at TestCatchError.main(TestCatchError.java:23)

  如此~

原文地址:https://www.cnblogs.com/Scott007/p/3093617.html