Java基础 - 异常

异常

一、异常体系结构

image-20210209155800288
  1. Error(灾难性的致命错误)
  • Error 类对象由 Java 虚拟机生成并抛出,大多数错误与代码编写者所执行的操作无关
  • 当 JVM 不再有继续执行操作所需要的内存资源时,将出现 OutOfMemoryError,此时 JVM 一般会选择线程终止
  • Error 是不可查的,因为它们在应用程序的控制和处理能力之外,而且绝大多数是程序运行时不允许出现的状况
  1. Exception
  • 这些异常一般是由程序逻辑错误引起的

二、异常处理机制

  • 关键字:try(监控区域)、catch(捕获异常)、finally(善后处理)、throw、throws
  • 快捷键:Ctrl + Alt + t
try {
    System.out.println(a/b);
}catch (ArithmeticException e){     	 //try中代码块出现ArithmeticException异常时,执行catch中的代码快
    System.out.println("出现异常:ArithmeticException");
    e.printStackTrace();    			//printStackTrace(System.err)   打印错误的栈信息
}catch (Throwable t){               //可以存在多个catch,但是下方捕获异常范围要大于上方捕获异常范围【Throwable>ArithmeticException】
    System.out.println("出现异常:Throwable");
}finally {                      //无论try中代码快是否出现异常,都会执行【IO流关闭文件等善后工作】
    System.out.println("finally");
}
public static void main(String[] args) {
    test1(1,0);
}
public static void test1(int a,int b) {
    if (b==0){
        throw new ArithmeticException();    		//throw在方法中主动的抛出异常
    }
}
public static void main(String[] args) {
    try {
        test1(1,0);
    } catch (ArithmeticException e) {
        System.out.println("拜拜");
    }
}
public static void test1(int a,int b) throws ArithmeticException {		//throws声明该方法可能出现的异常,然后在调用时进行捕获处理
    if (b==0){
        throw new ArithmeticException();
    }
}

三、自定义异常

  1. 创建自定义异常类
  2. 在方法中通过throw抛出异常对象
  3. 如果在当前抛出异常的方法中处理异常,可以使用try-catch语句捕获并处理;否则在方法的声明处通过throws致命要抛出给方法调用者的异常,继续进行下一步操作
  4. 在出现异常方法的调用者中捕获并处理异常
public class Blank {
    public static void test(int value) throws MyException {
        if (value>10){
            throw new MyException(value);
        }else {
            System.out.println("没毛病");
        }
        System.out.println("拜拜");
    }
    public static void main(String[] args) {
        try {
            test(11);
        } catch (MyException e) {
            e.printStackTrace();
        }
    }
}

class MyException extends Exception{		//自定义异常
    private int num;
    public MyException(int a) {
        this.num = a;
    }
    @Override
    public String toString() {
        return "MyException{" +
                "num=" + num +
                '}';
    }
}
posted @ 2021-02-19 17:46  葬花骨  阅读(65)  评论(0)    收藏  举报