Java异常

一、异常Throwable类程序在运行时出现的不正常现象;位于java.lang包;

二、异常分类:

  1.Error类:(严重)

  2.Exception类:(不严重)

    (2.1RuntimeException:运行时异常,可处理,可不处理;

    (2.2CheckedException:受查异常,必须处理,否则无法编译;

    //受查异常也称编译异常;除了RuntimeException和它的子类,其他异常均为编译异常;

三、异常产生:

  1.自动抛出异常:当程序在运行时遇到不符合规范的代码或结果时,会产生异常,由JVM自动抛出;

  2.手动抛出异常:语法:throw new 运行时异常类型("实际参数") 

  //如果其它方法调用抛出或声明异常的方法,则此方法也要抛出、声明或者捕获异常;

  3.产生异常结果:相当于遇到return语句,导致程序因异常终止;

四、异常声明:throws//子类或实现类中的声明异常类型必须比父类小;

五、throw和throws的不同:

  1.throws使用在函数上;throw使用在函数内;(函数上:小括号和大括号之间)

  2.throws后面为异常类,可以多个,用逗号隔开;throw后面为异常对象;

六、异常处理:

  try {需要检测的代码}

  catch (Exception e) {处理异常的代码;(处理方式)}

  finally {一定会执行语句;常用于释放资源}

七、对捕获异常方法操作:

  1.String e.getMessage();异常信息;

  2.String e.toString();异常名称+异常信息;

  3.e.printStackTrace();异常名称+异常信息+异常来源位置;

七、throw抛出RuntimeException:无需throws声明;

八、自定义异常:继承Exception;

 

class FuShuException extends Exception{
    /*private String msg;
    FuShuException(String msg){
        this.msg=msg;
    }
    public String getMessage(){
        return msg;
    }*/
    FuShuException(String msg){
        super(msg);
    }
}
class Outer{
    int div(int a,int b) throws FuShuException{
        if (b<0){
            throw  new FuShuException("123");
        }
        return a/b;
    }
}
public class test{
    public static void main(String[] args){
        Outer d = new Outer();
        try{
            int x = d.div(4, -1);
            System.out.println(x);
        }
        catch (FuShuException e){
            System.out.println(e.toString());
            System.out.println(e.getMessage());
        }
    }
}

 

posted @ 2019-07-22 22:52  开拖拉机的拉风少年  阅读(127)  评论(0编辑  收藏  举报