自定义异常类(两个数相加,若其中一个是负数,或两个加起来是负数,抛出异常)

class AddException extends Exception{                     //声明异常类
    String message;
    public AddException(int m,int n){
        message=m+"是负数或"+n+"是负数或"+m+n+"是负数,不符合要求。";
    }
    public String getString(){
        return message;
    }
}
class Add{
    public void add(int m,int n)throws AddException{      //异常的抛出
        if(m<=0||n<=0||m+n<=0){
            throw new AddException(m,n);
        }
        int sum=m+n;
        System.out.println("值是"+sum);
    }
}
public class Main{
    public static void main(String args[]) {
        Add a=new Add();
        try{                                             //异常的处理
            a.add(1,1);
            a.add(1,2);
            a.add(-1,1);
            System.out.println("到不了这一行");
        }catch (AddException e){                        //在catch后面也可以搞一个finally,最后不管有没有异常都要执行
            System.out.println(e.getString());
        }
    }
}


//注意:异常可以多次抛出,但最终必须要被捕获
public class Test {
    static void go() throws NegativeArraySizeException {
        int[] a = new int[-1];
    }

    static void hi() throws NegativeArraySizeException {
        go();
    }

    public static void main(String[] args) {
        try {
            hi();
        } catch (NegativeArraySizeException e) {
            System.out.println("捕获来自远方的异常");
        }
    }
}

 

 

 

posted @ 2022-05-13 20:27  HzzzzLi  阅读(59)  评论(0)    收藏  举报