一文搞懂Java异常

第8章 异常

本章学习目标

  • 知道编译时异常(受检异常)与运行时异常(非受检异常)
  • 掌握常见的几种异常或错误类型
  • 掌握try-catch结构的语法格式和执行特点
  • 掌握关键字finally的作用和特点
  • 掌握关键字throw的作用
  • 掌握关键字throws的作用
  • 知道throw与throws的区别
  • 了解Object类clone方法的重写

8.1 异常概述

8.1.1 认识Java的异常

  1. 什么是异常

    在使用计算机语言进行项目开发的过程中,即使程序员把代码写得尽善尽美,在系统的运行过程中仍然会遇到一些问题,因为很多问题不是靠代码能够避免的,比如:客户输入数据的格式问题,读取文件是否存在,网络是否始终保持通畅等等。

    异常 :指的是程序在执行过程中,出现的非正常的情况,如果不处理最终会导致JVM的非正常停止。

    异常指的并不是语法错误,语法错了,编译不通过,不会产生字节码文件,根本不能运行.

    异常也不是指逻辑代码错误而没有得到想要的结果,例如:求a与b的和,你写成了a-b

  2. 如何对待异常

    程序员在编写程序时,就应该充分考虑到各种可能发生的异常和错误,极力预防和避免,实在无法避免的,要编写相应的代码进行异常的检测、异常消息的提示,以及异常的处理。

  3. 异常的抛出机制

    Java中是如何表示不同的异常情况,又是如何让程序员得知,并处理异常的呢?

    Java中把不同的异常用不同的类表示,一旦发生某种异常,就通过创建该异常类型的对象,并且抛出,然后程序员可以catch到这个异常对象,并处理,如果无法catch到这个异常对象,那么这个异常对象将会导致程序终止。

    运行下面的程序,程序会产生一个数组索引越界异常ArrayIndexOfBoundsException。我们通过图解来解析下异常产生和抛出的过程。

    工具类

    public class ArrayTools {
                // 对给定的数组通过给定的角标获取元素。
                public static int getElement(int[] arr, int index) {
                    int element = arr[index];
                    return element;
                }
            }

    测试类

    public class ExceptionDemo {
                public static void main(String[] args) {
                    int[] arr = { 34, 12, 67 };
                    int num = ArrayTools.getElement(arr, 4);
                    System.out.println("num=" + num);
                    System.out.println("over");
                }
            }

    上述程序执行过程图解:

    1562772282750.png异常产生过程.png

8.1.2 Java异常体系

  1. Throwable

    `java.lang.Throwable` 类是Java语言中所有错误或异常的超类。

    只有当对象是此类(或其子类之一)的实例时,才能通过Java 虚拟机或者Java的`throw` 语句抛出。类似地,只有此类或其子类之一才可以是 `catch` 子句中的参数类型。

  2. Error和Exception

    `Throwable`有两个直接子类:`java.lang.Error`与`java.lang.Exception`,平常所说的异常指`java.lang.Exception`。

    Error:表示严重错误,一旦发生必须停下来查看问题并解决问题才能继续,无法仅仅通过try...catch解决的错误。(如果拿生病做比喻,就像是突发疾病,而且是危重症,必须立刻停下来治疗而不是靠短暂休息、吃药、打针、或小手术简单解决处理)

    例如:StackOverflowError(栈内存溢出)和OutOfMemoryError(堆内存溢出,简称OOM)。

    Exception:表示普通异常,其它因编程错误或偶然的外在因素导致的一般性问题,程序员可以通过代码的方式检测、提示和纠正,使程序继续运行,但是只要发生也是必须处理,否则程序也会挂掉。(这就好比普通感冒、阑尾炎、牙疼等,可以通过短暂休息、吃药、打针、或小手术简单解决,但是也不能搁置不处理,不然也会要人命)。

    例如:空指针访问、试图读取不存在的文件、网络连接中断、数组下标越界等

    无论是Error还是Exception,还有很多子类,异常的类型非常丰富。当代码运行出现异常时,特别是我们不熟悉的异常时,不要紧张,把异常的简单类名,拷贝到API中去查去认识它即可。

    简单的异常查看.bmp

8.1.3 受检异常和非受检异常

我们平常说的异常就是指Exception,根据代码的编写编译阶段,编译器是否会警示当前代码可能发生xx异常,并督促程序员提前编写处理它的代码为依据,可以将异常分为:

  • 编译时期异常(即checked异常、受检异常):在代码编译阶段,编译器就能明确警示当前代码可能发生(不是一定发生)xx异常,并督促程序员提前编写处理它的代码。如果程序员不听话,没有编写对应的异常处理代码,则编译器就会发威,直接判定编译失败,从而程序无法执行。通常,这类异常的发生不是由程序员的代码引起的,或者不是靠加简单判断就可以避免的,例如:FileNotFoundException(文件找不到异常)。
  • 运行时期异常(即runtime异常、unchecked非受检异常):即在代码编译阶段,编译器完全不做任何检查,无论该异常是否会发生,编译器都不给出任何提示。只有等代码运行起来并确实发生了xx异常,它才能被发现。通常,这类异常是由程序员的代码编写不当引起的,只要稍加判断,或者细心检查就可以避免的。例如:ArrayIndexOutOfBoundsException数组下标越界异常,ClassCastException类型转换异常。
1562771528807.png

8.1.4 演示常见的错误和异常

  1. Error

    最常见的就是VirtualMachineError,它有两个经典的子类:StackOverflowError、OutOfMemoryError。

    package com.atguigu.exception;
    
            import org.junit.Test;
    
            public class TestStackOverflowError {
                @Test
                public void test01() {
                    //StackOverflowError
                    digui();
                }
    
                public void digui() {
                    digui();
                }
            }
    package com.atguigu.exception;
    
            import org.junit.Test;
    
            public class TestOutOfMemoryError {
                @Test
                public void test02() {
                    //OutOfMemoryError
                    //方式一:
                    int[] arr = new int[Integer.MAX_VALUE];
                }
                @Test
                public void test03() {
                    //OutOfMemoryError
                    //方式二:
                    StringBuilder s = new StringBuilder();
                    while (true) {
                        s.append("atguigu");
                    }
                }
            }
  2. 非受检的运行时异常

    package com.atguigu.exception;
    
            import org.junit.Test;
    
            import java.util.Scanner;
    
            public class TestRuntimeException {
                @Test
                public void test01() {
                    //NullPointerException
                    int[][] arr = new int[3][];
                    System.out.println(arr[0].length);
                }
    
                @Test
                public void test02() {
                    //ClassCastException
                    Object obj = 15;
                    String str = (String) obj;
                }
    
                @Test
                public void test03() {
                    //ArrayIndexOutOfBoundsException
                    int[] arr = new int[5];
                    for (int i = 1; i <= 5; i++) {
                        System.out.println(arr[i]);
                    }
                }
    
                @Test
                public void test04() {
                    //InputMismatchException
                    Scanner input = new Scanner(System.in);
                    System.out.print("请输入一个整数:");//输入非整数
                    int num = input.nextInt();
                    input.close();
                }
    
                @Test
                public void test05() {
                    int a = 1;
                    int b = 0;
                    //ArithmeticException
                    System.out.println(a / b);
                }
            }
  3. 受检的编译时异常

    package com.atguigu.exception;
    
            import org.junit.Test;
    
            import java.io.FileInputStream;
    
            public class TestCheckedException {
                @Test
                public void test06() {
                    Thread.sleep(1000);//休眠1秒,编译报错
                }
    
                @Test
                public void test07()  {
                    FileInputStream fis = new FileInputStream("Java学习秘籍.txt");//编译报错
                }
    
            }

8.2 异常的处理

Java异常处理的五个关键字:try、catch、finally、throw、throws

8.2.1 捕获异常:try…catch

当某段代码可能发生异常,不管这个异常是编译时异常(受检异常)还是运行时异常(非受检异常),我们都可以使用try块将它括起来,并在try块下面编写catch分支尝试捕获对应的异常对象。

try...catch语法格式:

try{
     可能发生xx异常的代码
}catch(异常类型1  e){
     处理异常的代码1
}catch(异常类型2  e){
     处理异常的代码2
}
....
try{
     可能发生xx异常的代码
}catch(异常类型1 | 异常类型2  e){
     处理异常的代码1
}catch(异常类型3  e){
     处理异常的代码2
}
....
  1. try{}中编写可能发生xx异常的业务逻辑代码。
  2. catch分支,分为两个部分,catch()中编写异常类型和异常参数名,{}中编写如果发生了这个异常,要做什么处理的代码。如果有多个catch分支,并且多个异常类型有父子类关系,必须保证小的子异常类型在上,大的父异常类型在下。
  3. 在catch分支中如何获取异常信息,Throwable类中定义了一些查看方法:
  • `public String getMessage()`:获取异常的描述信息,原因(提示给用户的时候,就提示错误原因。
  • `public void printStackTrace()`:打印异常的跟踪栈信息并输出到控制台。

包含了异常的类型,异常的原因,还包括异常出现的位置,在开发和调试阶段,都得使用printStackTrace。

  1. 执行流程
  • 如果在程序运行时,try块中的代码没有发生异常,那么catch所有的分支都不执行。
  • 如果在程序运行时,try块中的代码发生了异常,根据异常对象的类型,将从上到下选择第一个匹配的catch分支执行。此时try中发生异常的语句下面的代码将不执行,而整个try...catch之后的代码可以继续运行。
  • 如果在程序运行时,try块中的代码发生了异常,但是所有catch分支都无法匹配(捕获)这个异常,那么JVM将会终止当前方法的执行,并把异常对象“抛”给调用者。如果调用者不处理,程序就挂了。

示例代码:

package com.atguigu.test;

import java.util.Scanner;

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

        Scanner input = new Scanner(System.in);

        int m;
        while (true) {
            try {
                System.out.print("请输入一个正整数:");
                m = input.nextInt();

                if (m < 0) {
                    System.out.println("输入有误," + m + "不是正整数!");
                } else {
                    break;
                }
            } catch (InputMismatchException e) {
                //String result = input.nextLine();
                //System.out.println("输入有误," + result + "不是整数");
                e.printStackTrace();
            }
        }

        System.out.println("m = " + m);
    }
}

8.2.2 finally块

  1. finally块

    因为异常会引发程序跳转,从而会导致有些语句执行不到。而程序中有一些特定的代码无论异常是否发生,都需要执行。例如,IO流的关闭,数据库连接的断开等。这样的代码通常就会放到finally块中。

     try{
                 
             }catch(...){
                 
             }finally{
                 无论try中是否发生异常,也无论catch是否捕获异常,也不管try和catch中是否有return语句,都一定会执行
             }
             
              或
               try{
                 
             }finally{
                 无论try中是否发生异常,也不管try中是否有return语句,都一定会执行。
             } 

    注意:finally不能单独使用。

    当只有在try或者catch中调用退出JVM的相关方法,例如System.exit(0),此时finally才不会执行,否则finally永远会执行。

    示例代码:

    package com.atguigu.keyword;
    
            import java.util.InputMismatchException;
            import java.util.Scanner;
    
            public class TestFinally {
                public static void main(String[] args) {
                    Scanner input = new Scanner(System.in);
                    try {
                        System.out.print("请输入第一个整数:");
                        int a = input.nextInt();
                        System.out.print("请输入第二个整数:");
                        int b = input.nextInt();
                        int result = a / b;
                        System.out.println(a + "/" + b + "=" + result);
                    } catch (InputMismatchException e) {
                        System.out.println("数字格式不正确,请输入两个整数");
                    } catch (ArithmeticException e) {
                        System.out.println("第二个整数不能为0");
                    } finally {
                        System.out.println("程序结束,释放资源");
                        input.close();
                    }
                }
            }

  2. finally与return

    finally中写了return语句,那么try和catch中的return语句就失效了,最终返回的是finally块中的

    形式一:从try回来

    public class TestReturn {
                public static void main(String[] args) {
                    int result = test("12");
                    System.out.println(result);
                }
    
                public static int test(String str) {
                    try {
                        Integer.parseInt(str);
                        return 1;
                    } catch (NumberFormatException e) {
                        return -1;
                    } finally {
                        System.out.println("test结束");
                    }
                }
            }

    形式二:从catch回来

    public class TestReturn {
                public static void main(String[] args) {
                    int result = test("a");
                    System.out.println(result);
                }
    
                public static int test(String str) {
                    try {
                        Integer.parseInt(str);
                        return 1;
                    } catch (NumberFormatException e) {
                        return -1;
                    } finally {
                        System.out.println("test结束");
                    }
                }
            }

    形式三:从finally回来

    public class TestReturn {
                public static void main(String[] args) {
                    int result = test("a");
                    System.out.println(result);
                }
    
                public static int test(String str) {
                    try {
                        Integer.parseInt(str);
                        return 1;
                    } catch (NumberFormatException e) {
                        return -1;
                    } finally {
                        System.out.println("test结束");
                        return 0;
                    }
                }
            }

8.2.3 手工抛出异常对象:throw

  1. 异常对象生成的两种方式
    • 由虚拟机自动生成:程序运行过程中,虚拟机检测到程序发生了问题,就会在后台自动创建一个对应异常类的实例对象并抛出——自动抛出。适用于核心类库中预定义的异常类型。
    • 由开发人员手动创建:new 异常类型(【实参列表】);,如果创建好的异常对象不抛出对程序没有任何影响,和创建一个普通对象一样,但是一旦throw抛出,就会对程序运行产生影响了。适用于预定义类型和自定义异常。
  2. throw异常对象的语法格式

    throw new 异常类名(【参数】);

    throw语句抛出的异常对象,和JVM自动创建和抛出的异常对象一样,需要处理。如果没有被try..catch合理的处理,也会导致程序崩溃。

    throw语句会导致程序执行流程被改变,throw语句是明确抛出一个异常对象,因此它下面的代码将不会执行,如果当前方法没有try...catch处理这个异常对象,throw语句就会代替return语句提前终止当前方法的执行,并返回一个异常对象给调用者。

    package com.atguigu.throwdemo;
    
            public class TestThrow {
                public static void main(String[] args) {
                    try {
                        System.out.println(max(4, 2, 31, 1));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    try {
                        System.out.println(max(4));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    try {
                        System.out.println(max());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
    
                public static int max(int... nums) {
                    if (nums == null || nums.length == 0) {
                        throw new IllegalArgumentException("没有传入任何整数,无法获取最大值");
                    }
                    int max = nums[0];
                    for (int i = 1; i < nums.length; i++) {
                        if (nums[i] > max) {
                            max = nums[i];
                        }
                    }
                    return max;
                }
            }

8.2.4 声明方法可能抛出的异常:throws

  1. throws编译时异常

    如果在编写方法体的代码时,某句代码可能发生某个编译时异常,不处理编译不通过,但是在当前方法体中可能不适合处理或无法给出合理的处理方式,就可以通过throws在方法签名中声明该方法可能会发生xx异常,需要调用者处理。

    声明异常格式:

    修饰符 返回值类型 方法名(参数) throws 异常类名1,异常类名2…{   }

    在throws后面可以写多个异常类型,用逗号隔开。

    package com.atguigu.test;
    
            public class Triangle {
                private final double a;
                private final double b;
                private final double c;
    
                public Triangle(double a, double b, double c) throws Exception {
                    if (a <= 0 || b <= 0 || c <= 0) {
                        throw new Exception("三角形的边长必须是正数,不能为负数");
                    }
                    if (a + b <= c || b + c <= a || a + c <= b) {
                        throw new Exception(a + "," + b + "," + c + "不能构造三角形,三角形任意两边之后必须大于第三边");
                    }
                    this.a = a;
                    this.b = b;
                    this.c = c;
                }
    
                public double getA() {
                    return a;
                }
    
                public double getB() {
                    return b;
                }
    
                public double getC() {
                    return c;
                }
    
                @Override
                public String toString() {
                    return "Triangle{" +
                            "a=" + a +
                            ", b=" + b +
                            ", c=" + c +
                            '}';
                }
            }
    package com.atguigu.test;
    
            public class TestThrows {
                public static void main(String[] args)  {
                    try {
                        Triangle t1 = new Triangle(2, 2, 3);
                        System.out.println("三角形1创建成功:" + t1);
                    } catch (Exception  e) {
                        System.err.println("三角形1创建失败");
                        e.printStackTrace();
                    } 
                    try {
                        Triangle t2 = new Triangle(1, 1, 3);
                        System.out.println("三角形2创建成功:" + t2);
                    } catch (Exception e) {
                        System.err.println("三角形2创建失败");
                        e.printStackTrace();
                    } 
                }
            }
  2. throws运行时异常

    当然,throws后面也可以写运行时异常类型,只是运行时异常类型,写或不写对于编译器和程序执行来说都没有任何区别。如果写了,唯一的区别就是调用者调用该方法后,使用try...catch结构时,IDEA可以获得更多的信息,需要添加什么catch分支。

    package com.atguigu.test;
    
            public class TestThrowsRuntimeException {
                public static void main(String[] args) {
                    try {
                        System.out.println(divide(1, 2));
                    } catch (ArithmeticException e) {
                        throw new RuntimeException(e);
                    }
                }
    
                public static int divide(int a, int b) throws ArithmeticException {
                    return a / b;
                }
            }

8.3 方法重写对于throws要求

  1. 方法重写对于throws要求

    方法重写时,对于方法签名是有严格要求的:

    1. 方法名必须相同
    2. 形参列表必须相同
    3. 返回值类型
    • 基本数据类型和void:必须相同
    • 引用数据类型:<=
    1. 权限修饰符:>=,而且要求父类被重写方法在子类中是可见的
    2. 不能是static,final修饰的方法
    3. throws异常列表要求
    • 如果父类被重写方法的方法签名后面没有 “throws 编译时异常类型”,那么重写方法时,方法签名后面也不能出现“throws 编译时异常类型”。
    • 如果父类被重写方法的方法签名后面有 “throws 编译时异常类型”,那么重写方法时,throws的编译时异常类型必须<=被重写方法throws的编译时异常类型,或者不throws编译时异常。
    • 方法重写,对于“throws 运行时异常类型”没有要求。
    package com.atguigu.keyword;
    
            import java.io.IOException;
    
            public class TestOverride {
    
            }
    
            class Father {
                public void method() throws Exception {
                    System.out.println("Father.method");
                }
            }
            class Son extends Father {
                @Override
                public void method() throws IOException, ClassCastException {
                    System.out.println("Son.method");
                }
            }
  2. Object的clone方法和java.lang.Cloneable接口

    在java.lang.Object类中有一个方法:

    protected Object clone() throws CloneNotSupportedException 

    所有类型都可以重写这个方法,它是获取一个对象的克隆体对象用的,就是造一个和当前对象各种属性值一模一样的对象。当然地址肯定不同。

    我们在重写这个方法后时,调用super.clone(),发现报异常CloneNotSupportedException,因为我们没有实现java.lang.Cloneable接口。

    class Teacher implements Cloneable {
                private int id;
                private String name;
                public Teacher(int id, String name) {
                    super();
                    this.id = id;
                    this.name = name;
                }
                public Teacher() {
                    super();
                }
                public int getId() {
                    return id;
                }
                public void setId(int id) {
                    this.id = id;
                }
                public String getName() {
                    return name;
                }
                public void setName(String name) {
                    this.name = name;
                }
                @Override
                public String toString() {
                    return "Teacher [id=" + id + ", name=" + name + "]";
                }
                @Override
                public Teacher clone() throws CloneNotSupportedException {
                    return (Teacher) super.clone();
                }
    
            }
    public class TestClonable {
                public static void main(String[] args) throws CloneNotSupportedException {
                    Teacher src = new Teacher(1, "柴老师");
                    Teacher clone = src.clone();
                    System.out.println(clone);
                    System.out.println(src);
                    System.out.println(src == clone);
                }
            }