Java异常

异常是什么?

  程序运行时,发生可不被期望的事件,它阻止了程序按照程序猿的预期正常执行。

异常的机构体系

简单异常的处理

一个被除数为0的算术异常

 1 public static void main(String[] args){
 2 
 3         try {
 4             System.out.println("========计算开始========");
 5             int i = 1;
 6             int j = 0;
 7             //发生异常,产生异常类的实例化对象
 8             System.out.println("输出结果:"+i/j);
 9             System.out.println("========计算结束========");
10         } catch (ArithmeticException e) {//异常发生后回去匹配catch块的异常类,进行异常的处理
11             System.out.println(e.getMessage());
12         } finally {//异常的同一出口,没有finally会按照返回调用处或者结束
13             System.out.println("finally");
14         }
15 
16     }

关键字throws和throw

public static void main(String[] args) {
        try {
            System.out.println("========计算开始========");
            int i = 1;
            int j = 0;
            //发生异常,产生异常类的实例化对象
            System.out.println("输出结果:" + div(i, j));
            System.out.println("========计算结束========");
        } catch (ArithmeticException e) {//异常发生后回去匹配catch块的异常类,进行异常的处理
            System.out.println(e.getMessage());
        } finally {//异常的同一出口,没有finally会按照返回调用处或者结束
            System.out.println("finally");
        }

    }
    //throws 关键字表示此方法不处理异常,将异常往上层抛,将异常交由异常的调用方处理
    private static int div(int i, int j) throws ArithmeticException {
        return i / j;
    }
    //直接抛出异常的实例化对象
    private static void throwException(){
        throw new RuntimeException("额(⊙﹏⊙)我挂了...");
    }

Exception 和RuntimeException的区别

  从上面的异常结构我们知道RuntimeException是Exception的子类

 

posted @ 2019-05-08 21:48  恋旧的拾荒者  阅读(117)  评论(0编辑  收藏  举报