异常

异常

Exception

// 异常
public class Demo01 {
    public static void main(String[] args) {
        // System.out.println(11/0);
    }
}

运行结果:

简单分类

  • 检查性异常:最具代表的检查性异常是用户错误或问题引起的异常
  • 运行时异常
  • 错误ERROR:错误不是异常,而是脱离程序员控制的问题。

异常体系结构

  • Java把异常当作对象来处理,并定义一个基类java.lang.Throwable作为所有异常的超类

  • 在Java API中已经定义了许多异常类,这些异常类分为两大类,错误Error和异常Exception

java异常体系结构详解

异常处理机制

  • 抛出异常
  • 捕获异常
  • 异常处理五个关键字
    • try、catch、finally、throw、throws
public class Test {
    public static void main(String[] args) {
        int a = 1;
        int b = 0;

        try{
            if (b==0){// throw throws
                throw new ArithmeticException();// 主动的抛出异常
            }
            System.out.println(a/b);
            // 假设要捕获多个异常: 从小到大!
        }catch (Error e){// catch(想要捕获的异常类型) 捕获异常
            System.out.println("Error");
        }catch (Exception e){
            System.out.println("Exception");
        }catch (Throwable e){
            System.out.println("Throwable");
        }finally {// 处理善后工作
            System.out.println("finally");
        }
        // finally 可以不要 finally, 假设IO, 资源,关闭!
    }

运行结果:

public class Test2 {
    public static void main(String[] args) {
        int a = 1;
        int b = 0;
        // 选中 Ctrl+ Alt + T try/catch/finally
        try {
            System.out.println(a/b);
        } catch (Exception e) {
            // System.exit(1); 程序手动结束
            e.printStackTrace();// 打印错误的栈信息
        } finally {
        }
    }
}

运行结果:

public class Test {
    public static void main(String[] args) {

        try {
            new Test().test(1, 0);
        } catch (ArithmeticException e) {
            e.printStackTrace();
        }
    }
        // 假设这方法中,处理不了这个异常,方法上抛出异常
        public void test ( int a, int b){
            if (b == 0) {// throw throws
                throw new ArithmeticException();// 主动的抛出异常
            }
        }
}

运行结果:

自定义异常

  1. 创建自定义异常类
  2. 在方法中通过throw关键字抛出异常对象
  3. 如果在当前抛出异常的方法中处理异常,可以使用try-catch语句捕获并处理;否则在方法的声明处通过throws关键字指明要抛出给方法调用者的异常,继续进行下一步操作
  4. 在出现异常方法的调用者中捕获并处理异常
// 自定义异常类
public class MyException extends Exception{
    // 传递数字>10;
    private int detail;
    public MyException(int a) {
        this.detail = a;
    }
    // toString:异常的打印信息
    @Override
    public String toString() {
        return "MyException{" + detail + '}';
    }
}
public class Test {
    // 可能会存在的方法
    static void test(int a) throws MyException {
        System.out.println("传递的参数为:"+a);
        if (a>10){
            throw new MyException(a);// 抛出
        }
        System.out.println("OK");
    }
    public static void main(String[] args) {
        try {
            test(11);
        } catch (MyException e){
            // 增加一些处理异常的代码~
            System.out.println("MyException=>"+e);
        }
    }
}

运行结果:

推荐免费课程

posted @ 2021-05-10 20:42  闲着的大叔  阅读(42)  评论(0编辑  收藏  举报