章12——异常exception

gknives / 2024-09-17 / 原文

异常
快捷键 ctrl + alt + t
选中 try-catch
如果进行异常处理,即使出现了异常,程序可以继续执行。

异常介绍
开发过程中的语法错误和逻辑错误不是异常。
执行过程中所发生的异常事件可分为如下两大类:

异常体系图


小结:

常见的运行时异常

没有关联的类不能进行上下转型

异常处理机制
两种:try-catch 和 throws

比如如果try中有些重要的资源一定要关闭,那么我们就可以把资源的关闭放到finally代码块中。
如果没有finally也是允许的。
快捷键:ctrl + alt + t

最终传回JVM时:处理机制:
第一步:输出异常信息
第二步:中断程序

当我们对异常没有处理时(没有显式地使用 try-catch 或 throw),默认时有个throws

public class TryCatchDetail {
    public static void main(String[] args) {
        try {
            String str = "abc";
            int a = Integer.parseInt(str);
            System.out.println(a);
        } catch (NumberFormatException e) {
            System.out.println("异常信息=" + e.getMessage());
        }finally {
            System.out.println("finally");
        }

        System.out.println("going on...");
    }
}


父子顺序:拒绝垄断。


但是此时我们的善后工作在finally中可以被执行。

练习实践:保证整数输入的 try-catch

import java.util.Scanner;

public class TryCatchExercise {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int num = 0;
        while (true){
            try {
                num = Integer.parseInt(scanner.next());
                break;
            } catch (NumberFormatException e) {
                //返回到循环起始点。
            }
        }
    }
}

throws异常处理

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

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

    }
    //使用抛出异常,让调用f1方法的调用者(常常是另一个方法)处理。
    //此处用父类Exception也可以。
    //throws关键字后也可以是 异常列表,即可以抛出多个异常。
    public void f1() throws FileNotFoundException, NullPointerException{
        FileInputStream fis = new FileInputStream("d://aa.txt");
    }
}

throws细节


而如果抛出了运行异常,则不用处理,如果抛出了编译异常,则要处理,不论方法中到底有没有该异常。

自定义异常

例子:

一般情况下,我们继承运行时异常,其好处在于,我们可以使用默认的处理机制。

throw 和 throws 的区别

本章作业
没太明白

public class EcmDef {
    public static void main(String[] args) {
        //需要在程序中配置参数
        EcmDef ecmDef = new EcmDef();
        try {
            if(args.length !=2){
                throw new ArrayIndexOutOfBoundsException("参数个数不对");
            }

            int n1 = Integer.parseInt(args[0]);
            int n2 = Integer.parseInt(args[1]);

            double res = ecmDef.cal(n1,n2);

            System.out.println(res);
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println(e.getMessage());
        }catch (NumberFormatException e){
            System.out.println("参数格式不对");
        }catch (ArithmeticException e){
            System.out.println("出现了除0的异常");
        }

    }
    public double cal(int n1, int n2){
        return n1/n2;
    }
}