java学习之异常之运行异常

Exception中有一个特殊的子类异常:

RuntimeException:(运行时异常):

1.如果在函数内抛出该异常,函数上可以不用声明,编译一样通过。

2.如果在函数上声明了该异常,调用者可以不用经行处理,编译一样通过。

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

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

对于异常分两种:

1.编译时被检测的异常

2.编译时不被检测的异常(运行时异常。RuntimeException以及其子类)

package com.dreamy.day04;

/**
 * @author dreamy
 *
 */
class FuShuException extends RuntimeException{
    public FuShuException(String msg) {
        super(msg);
    }
}
class Demo03{
    int div(int a,int b) {//throws Exception
        
//e instanceof RuntimeException
        
        if(b<0) {
            throw new FuShuException("出现了除数为负数了");
        }
        if(b==0) {

            throw new ArithmeticException("除零啦");
        }
        return a/b;
    }
}
public class RuntimeExceptionDemo01 {

    public static void main(String[] args) {
        Demo03 d=new Demo03();
        int x=d.div(4, -1);
        System.out.println("x:"+x);
        System.out.println("over");
        
//        Person p=new Person();
//        p.checkName(null);
    }
}
/*class Person{
    public void checkName(String name) {
        //if(name.equals("lisi")) {//NullPointerException
        if("lisi".equals(name)) {//if(name!=null&&name.equals("lisi"))
            System.out.println("YES");
        }else {
            System.out.println("NO");
        }
    }
}*/

 

posted @ 2017-12-15 17:50  dreamy_java  阅读(182)  评论(0编辑  收藏  举报