day09-11-面向对象(RuntimeException)

2020-05-21  本文已影响0人  姗婷

Exception中有一个特殊的子类异常RuntimeException运行时异常
如果在函数内容抛出该异常,函数可以不用声明,编译一样通过

int div(int a,int b)
    {
        if(b==0)
            throw new ArithmeticException("被零除了");
        return a/b;
    }

如果在函数上声明了该异常,调用者可以不用进行处理,编译一样通过,调用者无需要处理(try catch或throws)

int div(int a,int b) throws ArithmeticException
    {
        //if(b==0)
            //throw new ArithmeticException("被零除了");
        return a/b;
    }

之所以不用再在函数声明,是因为不需要让调用者处理。
当该异常发生,希望程序停止,因为再运行时,出现了无法继续运算的情况,希望停止程序后,对代码进行修正

自定义异常时,如果该异常的发生,无法在继续进行运算,就让自定义异常继承RunTimeException

对于异常分两种:
1.编译时被检测的异常
2.编译时不被检测的异常(运行时异常,RuntimeException以及其子类: ArithmeticException:数学计算异常、NullPointerException:空指针异常、ArrayOutOfBoundsException:数组索引越界异常)

class FuShuException extends RuntimeException
{
    FuShuException(String msg)
    {
        super(msg);
    }   
}
class Demo
{
    int div(int a,int b) //throws ArithmeticException
    {
        if(b<0)
            throw new FuShuException("出现除数为负数了");//继承了RuntimeException也不需要声明
        if(b==0)
            throw new ArithmeticException("被零除了");
        return a/b;
    }
}
class ExceptionDemo4
{
    public static void main(String[] args)
    {
        Demo d = new Demo();
        int x = d.div(4,0);
        System.out.println("x="+x);
        System.out.println("over");
    }
}
上一篇 下一篇

猜你喜欢

热点阅读