异常的声明与抛出

下面对定义的类进行异常的处理,自己声明几个异常类型。

public class Loggerzs {

    int year;       //必须是1970-2018的整数
    int m;          //必须是1-12的整数
    int i;
    int[] d;
    public int getI() {
        return i;
    }

    public void setI(int i)throws NegativeArraySizeException{   //告诉调用者可能会出现的错误
        this.i = i;
        d=new int[i];
    }

    public int getYear() {
        return year;
    }

    public void setYear(int year){              //声明异常,在类的内部抛出异常
        if(year>1970&&year<2018){
            this.year = year;
        }else{
            try{
                throw new Exception("输入年超出范围");
            }catch(Exception e1){
                e1.printStackTrace();
            }
        }
    }

    public int getM() {
        return m;
    }

    public void setM(int m)throws Exception{        //声明异常,并且把异常抛给调用者
        if(m>=1&&m<=12){
            this.m = m;
        }else{
            throw new Exception("输入月份非法");
        }
    }
}
void run7(){
        Loggerzs log=new Loggerzs();
        Scanner putin=new Scanner(System.in);
        int i=putin.nextInt();
        if(i<=0)
            System.err.print("输入必须为正整数");

        try{
            log.setI(i);
        }catch(NegativeArraySizeException n1){      //调用的时候处理异常
            throw n1;
        }finally{
            System.out.println("抛出结束");
        }

        log.setYear(2016);      //异常处理在类里

        try {
            log.setM(5);        //抛给调用者,调用的时候处理异常
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
1.运行时异常:

即RuntimeException及其之类的异常。这类异常在代码编写的时候不会被编译器所检测出来,程序员可以根据需要进行捕获抛出。常见的RUNtimeException有:
NullpointException(空指针异常)
ClassCastException(类型转换异常)
IndexOutOfBoundsException(数组越界异常)
ArithmeticException( 数学运算异常)
ArrayStoreException(将数组类型不兼容的值赋值给数组元素时抛出的异常)
NegativeArraySizeException(数组负下标异常)
ClassCastException(数据类型转换异常)

2.编译异常:

RuntimeException以外的异常。这类异常在编译时编译器会提示需要捕获,如果不进行捕获则编译错误。常见编译异常有:IOException(流传输异常),SQLException(数据库操作异常)

exit(1);是唯一可以不执行finally直接退出虚拟机的方法,其他的情况都必然执行finally。

猜你喜欢

转载自blog.csdn.net/dt_zhangshuo/article/details/81168160
今日推荐