Java中异常的详细讲解与细节讨论

用一个代码引出异常为什么要使用异常

代码:

public static void main(Sting args[]){
    int n1 = 1;
    int n2 = 0;
    System.out.println(n1/n2);//这里会抛ArihmaticException,因为除数不能为0,若未用异常处理机制则程序直接结束,后面的代码将不执行。这样很不好,我们不能因为一个非致命的错误而结束整个程序
    .
    .
    .
}

异常的基本介绍:

        在Java中,异常是指在程序执行过程中发生的错误或异常情况。Java中的异常处理机制允许我们捕获和处理这些异常,以便程序能够继续执行或进行适当的处理。

异常分为两类:

        (1)编译时异常,是编译器要求解决的异常,必须解决,否则程序跑不起来。如:ClassNotFounfException(找不到类异常)...

        (2)运行时异常,编译器检查不出来,一般是指编程时的逻辑错误,程序员应当避免。如:NullPointerException(空指针异常),ArithmeticException(数学运算异常),ArrayIndexOutOfBoundsException(数组下标越界异常),ClassCastException(类型转换异常),NumberFormatException(数字格式不正确异常)...

NullPointerException(空指针异常)代码:

public class NullPointException {
    public static void main(String[] args) {
        //当应用程序试图在需要对象的地方使用null时,抛出该异常
        String name1 = null;
        String name2 = "";
        try {
            System.out.println(name1.length());//空指针
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(name2.length());

    }
}

ArithmeticException(数学运算异常)代码:

public class ArithmeticException {
    public static void main(String[] args) {
        //当出现异常的运算条件时,抛出此异常
        int n1 = 1;
        int n2 = 0;
        try {
            System.out.println(n1/n2);//除数不能为0
        } catch (Exception e) {
//            e.printStackTrace();
            System.out.println(e.getMessage());
        }
    }
}

 ArrayIndexOutOfBoundsException(数组下标越界异常)代码:

public class ArrayIndexOutOfBoundsException {
    public static void main(String[] args) {
        //用非法索引访问数组时抛出的异常
        int[] array = {1,2,3};
        for (int i = 0; i <= array.length; i++) {
            System.out.println(array[i]);//数组越界了,。没有array[3]
        }
    }
}

ClassCastException(类型转换异常)代码:

public class ClassCastException {
    public static void main(String[] args) {
        A b = new B();//向上转型
        B b2 = (B)b;//向下转型
        //当试图将对象强制转换为不是实例的子类时,抛出该异常
        C c = (C) b;//这里会抛出ClassCastException,因为B类和C类没有关系,并不能类型转换
    }
}

class A{}
class B extends A{}
class C extends A{}

 NumberFormatException(数字格式不正确异常)代码:

public class NumberFormatException {
    public static void main(String[] args) {
        String name2 = "123";
        int n2 = Integer.parseInt(name2);
        System.out.println(n2);

        //当应用程序试图将字符串转换成一种数值类型,但该字符串不能转换为适当格式时,抛出该异常
        //当要把字符串转换为数字时,但是该字符串不能转换为数字时抛出的异常
        String name1 = "ret";
        int n1 = Integer.parseInt(name1);//这里会抛出NumberFormatException,因为ret不能转换为数字
        System.out.println(n1);

    }
}

异常处理方式:

        (1)try-catch-finally,程序员在代码中捕获发生的异常,自行处理。(就地解决)

        (2)throws,将发生的异常抛出,交给调用者(方法)来处理,最顶级的处理者是JVM,而JVM的处理就是直接报错,结束程序

try-catch-finally处理机制示意图:

Java中异常的详细讲解与细节讨论_第1张图片

 throws处理机制示意图:

Java中异常的详细讲解与细节讨论_第2张图片

 try-catch-finally细节讨论:

        (1)如果try块中的异常发生了,则异常发生后面的代码不会执行,直接进入到 catch 块

        (2)如果异常没有发生,则顺序执行 try 的代码块,不会进入到 catch块中

        (3)如果希望不管是否发生异常,都执行某段代码(比如关闭连接,释放资源等)则将代码放在finally块中

代码:

public static void main(String args[]){
    try {
            String str = "ret";
            int a = Integer.parseInt(str);
            System.out.println("数字:" + a);
        } catch (Exception e) {
            System.out.println("异常信息=" + e.getMessage());
        } finally {
            System.out.println("finally的代码块被执行");
        }
    System.out.println("程序继续...");
    
}
/*
输出结果:
    异常信息=For input string: "ret"
    finally的代码块被执行
    程序继续...
*/

        (4)可以有多个catch语句,捕获不同的异常(进行不同的业务处理),要求父类异常在后,子类异常在前

代码:

public class TryCatchFinallyDetails {
    public static void main(String[] args) {
        //1.如果 try 代码块有可能有多个异常
        //2.可以使用多个 catch 分别捕获不同的异常,相应处理
        //3.要求子类异常写在前面,父类异常写在后面
        try {
            People people = new People();
            System.out.println(people.getName());//NullPointerException
            int n1 = 10;
            int n2 = 0;
            int res = n1 / n2;//ArithmeticException
        } catch (NullPointerException e) {
            System.out.println("空指针异常=" + e.getMessage());
        } catch (ArithmeticException e) {
            System.out.println("算术异常=" + e.getMessage());
        } catch (Exception e) {//Exception是ArithmeticException和NullPointerException的父类
            System.out.println(e.getMessage());
        } finally {
            System.out.println("执行finally语句");
        }
    }
}

class People {
    private String name = "ret";
    public String getName() {
        return name;
    }
}

/*
    输出结果:
    ret
    算术异常=/ by zero
    执行finally语句
*/

        (5)可以进行 try-finally 配合使用, 这种用法相当于没有捕获异常,因此程序会直接崩掉/退出。应用场景,就是执行一段代码,不管是否发生异常,都必须执行某个业务逻辑

代码:

public static void main(String[] args) {
/*
可以进行 try-finally 配合使用, 这种用法相当于没有捕获异常,
因此程序会直接崩掉/退出。应用场景,就是执行一段代码,不管是否发生异常,
都必须执行某个业务逻辑
*/
    try {
        int n1 = 10;
        int n2 = 0;
        System.out.println(n1 / n2);
    } finally {
        System.out.println("执行了 finally..");
    }
        System.out.println("程序继续执行..");
}

throws细节讨论: 

        (1)对于运行时异常,程序中如果没有处理,默认就是throws的方式处理

        (2)子类重写父类的方法时,对抛出异常的规定:子类重写的方法,所抛出的异常类型要么和父类抛出的异常一致,要么抛出的异常类型是父类抛出异常的子类型

        (3)在throws过程中,如果有try_catch,就相当于处理异常了,就不必throws了

代码:

package com.example.retcode.test.exception.throws_;

import java.io.FileInputStream;
import java.io.FileNotFoundException;

/**
 * @author ruientao
 * @version 1.0
 * 2023/8/21 21:11
 * @description TODO
 */
public class ThrowsDetails {
    public static void main(String[] args) {
        f2();
    }

    public static void f2() /*没有进行try_catch处理异常,就默认了throws,而且是throws ArithmeticException*/ {
        //1.对于编译异常,程序中必须处理,比如try-catch或者throws
        //2.对于运行时异常,程序中如果没有处理,默认就是throws的方式处理
        int n1 = 10;
        int n2 = 0;
        double res = n1 / n2;
    }

    public static void f1() throws FileNotFoundException {
        //调用f3()会报错
        //1. 因为 f3() 方法抛出的是一个编译异常,即这时,就要 f1() 必须处理这个编译异常,在f1()中,要么try-catch-finally,或者继续throws这个编译异常
        f3(); // 抛出异常
    }

    public static void f3() throws FileNotFoundException {
        FileInputStream fis = new FileInputStream("d://java.txt");
    }

    public static void f4() {
        //在 f4()中调用方法f5()是可以的,原因是f5()抛出的是运行异常
        //在java中,并不要求程序员显示处理,因为有默认处理机制
        f5();
    }

    public static void f5() throws ArithmeticException {
    }
}

class Father { //父类
    public void method() throws RuntimeException {
    }
}

class Son extends Father {//子类

    //子类重写父类的方法时,对抛出异常的规定:子类重写的方法,所抛出的异常类型要么和父类抛出的异常一致,要么为父类抛出的异常类型的子类型
    //在throws过程中,如果有方法try-catch,就相当于处理异常,就可以不必throws
    @Override
    public void method() throws ArithmeticException {
    }
}

自定义异常:

        当程序中出现了某种错误,但是错误信息并没有在Throwable子类中描述处理,这个时候可以自己设计异常类,用于描述该错误信息

细节讨论:

        (1)自定义异常类名(程序员自己定),继承Exception或RuntimeException

        (2)如果继承Exception,属于编译异常,如果继承RuntimeException,属于运行异常(一般来说继承RuntimeException,好处时,我们可以使用默认的处理机制,比较方便)

代码:

public class CustomException {
    public static void main(String[] args) /*throws AgeException*/ {
        int age = 158;
        //要求范围在 18 – 120 之间,否则抛出一个自定义异常
        if (!(age >= 18 && age <= 120)) {
            //这里我们可以通过构造器,设置信息
            try {
                throw new AgeException("年龄需要在 18~120 之间");
            } catch (AgeException e) {
                System.out.println(e.getMessage());
            }
        } else {
            System.out.println("你的年龄范围正确:" + age + "岁");
        }
    }
}

class AgeException extends RuntimeException {
    public AgeException(String message) {//构造器
        super(message);
    }
}

throw 和 throws 的区别

Java中异常的详细讲解与细节讨论_第3张图片

 

你可能感兴趣的:(java,开发语言)