JAVA-异常处理

耗尽温柔 提交于 2019-12-05 13:38:27

https://blog.csdn.net/michaelgo/article/details/82790253

Error类及其子类,RuntimeException类及其子类的异常不需要一定try catch包起来

Exception类及其子类(排除RuntimeException类及其子类)的一定要用try catch包起来

 

如下,可以编译通过

package exception;

public class test1 {
    public static void main(String[] args) {
        a();
    }
    
    static void a() throws a{
        a b=new a("异常了");
        throw b;
    }

}

class a extends RuntimeException{
    //异常信息
    private String message;

    //构造函数
    public a(String message){
        super(message);
        this.message = message;
    }

}

如下,编译报错

package exception;

public class test1 {
    public static void main(String[] args) {
        a();
    }
    
    static void a() throws a{
        a b=new a("异常了");
        throw b;
    }

}

class a extends Exception{
    //异常信息
    private String message;

    //构造函数
    public a(String message){
        super(message);
        this.message = message;
    }

}

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!