JAVA自定义异常

创建自定义异常是为了表示应用程序的一些错误类型,为代码可能发生的一个或多个问题提供新含义。

可区分代码运行时可能出现的相似问题的一个或多个错误,或给出应用程序中一组错误的特定含义。

//自定义异常类需要继承Exception

public class MyselfException extends Exception {

    private int detail;
    public MyselfException(int index){
        detail=index;
    }
    
    public String toString(){
        return "MyException["+detail+"]";
    }
}

//测试类

public class MyselfExceptionTest {
    static void test(int index)throws MyselfException{
        System.out.println("调用的方法参数是 :test("+index+")");
        if(index>10){
            throw new MyselfException(index);
        }
        System.out.println("没有发生异常");
    }
    
    
    public static void main(String[] args) {
        try {
            test(1);//无异常
            test(20);//异常
        } catch (Exception e) {
            System.out.println("发生异常:"+e);
            e.printStackTrace();
        }
    }
}

原文地址:https://www.cnblogs.com/laotan/p/4550569.html