基础4-高级-异常类

异常:程序在执行过程中,出现不正常的情况,最终导致JVM停止

分类

Throwable(顶级)
          -----Error(错误)
          -----Exception(编译异常)
                -----RuntimeException(运行异常)

编译异常:程序进行编译出错
运行异常:程序开始运行出错

原理


图片.png

方案

处理编译异常:抛出异常+捕获异常
处理运行异常:捕获异常

1、throw抛出
      ---throw关键字在方法内部
      ---throw关键字+异常对象

public class  HelloWorld {
    public static void main(String[] args) {
        String str  = null;
        if(str == null){
            //throw + 异常对象
            throw new NullPointerException();
        }
    }
}

2、throws关键字
      ---throws关键字在方法声明处
      ---throws关键字+异常类名


public class  HelloWorld {
    public static void main(String[] args) throws Exception {
        run();
    }
    public static void run() throws Exception{
        System.out.println("张三");
    }
}

3、try  catch语句

public class  HelloWorld {
    public static void main(String[] args) {
        try{
            int a = 10;
            int b = a / 0 ;
        }catch (Exception e){
            System.out.println("分母不能为0");
            return;
        }finally {
            System.out.println("释放资源");
        }
    }
}

Throwable

1、getMessage():打印少量异常信息
2、toString():打印少量异常信息
3、printStackTrace():打印最全异常信息(常用)


public class  HelloWorld {
    public static void main(String[] args) {
        Throwable throwable = new Throwable();
        System.out.println(throwable.getMessage());
        System.out.println(throwable.toString());
        System.out.println(throwable.printStackTrace(););
    }
}

自定义异常

//自定义异常:1、继承Exception 编译异常 2、继承 RuntimeException 运行异常
class newException extends Exception{

}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容