【javase09~异常】

2019-01-17  本文已影响0人  昵称该起什么好呢

【部分内容来自网络,侵删】

异常体系

ee.png

抛出异常

语法:throw new Exception('异常信息');

class Test {
    public static void main(String[] args) {
        int a = 1;
        int b = 0;
        if(b==0){
            throw new java.lang.ArithmeticException("被除数不能为0");
        }
        System.out.println(a/b);
    }
    
}

声明异常

class Test {
    public static void main(String[] args) throws ArithmeticException {
        int a = 1;
        int b = 0;
        System.out.println(a/b);
    }
    
}

捕获异常

class Test {
    public static void main(String[] args) {
        int a = 1;
        int b = 0;
        try{
            division(a,b);
        } catch(ArithmeticException e) {
            System.out.println("除数不能为0");
        } finally {
            System.out.println("程序最终执行到这里");    
        }
        
    }
    
    public static void division(int a, int b){
        System.out.println(a/b);
    }
    
}

运行时异常和编译时异常

  1. 运行时异常就是RuntimeException及其子类,调用者无需处理该类异常,通常来自于代码的逻辑问题。
  2. 编译期异常即非RuntimeException,如果抛出了该类异常,则或者进行捕获,或者进行向上抛出。

方法重写时的异常处理

自定义异常

上一篇 下一篇

猜你喜欢

热点阅读