java异常体系的详细解析

异常的定义

异常指的是程序在执行过程五中,出现的非正常的情况 ,最终会导致JVM的非正常停止。
在java面向对象编程语言中,异常本身就是一个类。异常指的并不是语法错误 。

异常体系

java.lang.Throwable类是java语言所有错误或异常的超类。
java异常体系

异常与错误的区别

  • Exception:是应用程序中出现的可预测,可恢复的问题,通常是轻度或中度的问题;把异常处理掉,程序可以正常运行。
  • Error:表示运行应用程序时比较严重的错误,绝大多数跟代码无关,比如操作系统出现错误,而导致程序出现错误无法运行。

根据异常体系结构图,Exception类有一个子类RuntimeException ,代表程序在运行过程中发生了异常,而导致程序无法正常往下运行,代码可以通过try catch对运行期异常进行捕获。

public class DemoException {
    public static void main(String[] args) throws ParseException {

        //Exception编译期异常:编写代码时,IDEA提示需对程序加入ParseException异常判断
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date date = simpleDateFormat.parse("2020-05--02");

        //RuntimeException:在程序运行过程中,以下代码中有可能会现数组越界
        //可以通过try catch进行异常捕获
        String[] strings = {"A", "B", "C"};
        try {
            System.out.println(strings[3]);
        } catch (ArrayIndexOutOfBoundsException e) {
            e.printStackTrace();
        }

        //Error:分配了一个内存超大的数组,导致系统发生OutOfMemoryError,程序崩溃
        int[] array = new int[1234 * 1234 * 1234 * 1234 * 1234 * 1234];

    }
}

Throwable类的三个常用方法

//返回简短描述
public String getMessage()
//返回详细消息字符串
public String toString()
//JVM打印异常对象,异常信息最全面,程序中一般会使用该方法
public void printStackTrace()

如何处理异常

1、异常发生的过程
	public static void main(String[] args) {
        String[] strings = {"A", "B", "C"};
        System.out.println(strings[3]);
    }
  1. 在程序中访问数组strings的索引位置3时,JVM会检测出程序发生异常,这时JVM创建一个异常对象(new ArrayIndexOutOfBoundsException(“3”) );
  2. 由于在程序中没有异常处理的逻辑(try catch),jvm就会把异常对象抛出给方法的调用者main主方法来处理这个异常;
  3. main主方法接收到这个异常对象,但自身也没有处理异常的任何逻辑,则只能把该异常对象再抛还给JVM。
  4. JVM接下来就会做以下两件事件:一、把异常对象(包含内容,原因、位置)以红字字体打印在控制台;二、中断当前正在执行的程序。
2、throw抛出异常

注意:程序中通过throw抛出的运行期异常,方法后边可不通过throws声明异常

在java程序代码中,可以使用throw关键字在指定的方法中抛出指定的异常。

  1. throw关键字必须写在方法的内部
  2. throw关键字后面new的对象必须是Exception对象或者子类对象。
  3. throw关键字抛出Exception异常对象,可以使用try catch进行捕获。
public static void main(String[] args) {

        String[] strings = {"A", "B", "C"};
        int index = 3;

        //代码判断查询索引超出数组范围,主动抛出异常
        if (index >= strings.length) {
            throw new ArrayIndexOutOfBoundsException("索引超出数组范围");
        }

        //通过try catch捕获异常,防止程序中断
        try {
            System.out.println(strings[index]);
        } catch (Exception e) {
            e.printStackTrace();
        }

        System.out.println("程序执行结束");

    }
3、throws关键字

注意:程序中通过throw抛出的编译期异常,方法后边必须通过throws声明异常

在方法声明时可以使用throws关键字,让方法可以进行异常对象的处理。

  1. throws关键字必须写在方法声明处,格式:修饰符 返回值类型 方法名(参数) throws Exception
  2. throws关键字后边声明的异常必须是Exception或其子类
  3. 方法内部如果抛出了多个异常对象,那么在方法处也必须跟上多个异常。
  4. 一个方法如果调用了throws声明异常的另一个方法,那么该方法也必须通过throws进行声明异常。
public class ThrowsException {
    //main方法调用了foundFile方法,由于foundFile声明了异常,则main方法也必须通过声明
    public static void main(String[] args) throws FileNotFoundException {
        foundFile("c:\\bbb.txt");

    }

    //在程序内部通过throw关键字抛出了编译期异常,则方法也必须声明异常
    public static void foundFile(String fileName) throws FileNotFoundException {
        if (!fileName.equals("c:\\aaa.txt")) {
            throw new FileNotFoundException("文件不存在");
        }
    }

    //在程序内部通过throw关键字抛出了两个异常对象,则方法也必须声明两类异常
    public static void createFile(String fileName) throws FileNotFoundException, FileAlreadyExistsException {
        if (!fileName.equals("c:\\aaa.txt")) {
            throw new FileNotFoundException("文件不存在");
        }
        throw new FileAlreadyExistsException("文件已存在");
    }

}
4、 使用try catch finally处理异常

以上通过throw抛出异常对象的处理异常的方式,会导致程序中断;为保证程序的持续运行,需要程序员在编写代码时对可能产生异常的代码通过try catch finally方式处理异常。

注意:
1、try中可能会抛出多个异常对象,那么就可以使用多个catch来处理这些异常对象
2、如果try中产生了异常,那么就会执行catch中的异常处理逻辑,执行完毕catch中的处理逻辑后,继续执行try catch之后的代码
3、如果try中不产生异常,那么执行完try中的代码后,则不会执行catch中的异常处理逻辑,而是继续执行try catch之后的代码.
4、finally块中的代码无论出现异常,都会执行:finally不能单独使用;finally一般用于资源释放。

public class TryCatchFinally {
    public static void main(String[] args) {
        //通过try catch捕获FileNotFoundException,只是打印异常,程序得以继续运行
        try {
            foundFile("c:\\bbb.txt");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            System.out.println("释放资源");
        }

        System.out.println("程序继续运行");

    }

    //在程序内部通过throw关键字抛出了编译期异常,则方法也必须声明异常
    public static void foundFile(String fileName) throws FileNotFoundException {
        if (!fileName.equals("c:\\aaa.txt")) {
            throw new FileNotFoundException("文件不存在");
        }
    }
}

原创文章 56 获赞 8 访问量 4724

猜你喜欢

转载自blog.csdn.net/jpgzhu/article/details/105890623
今日推荐