文章目录:
  1. 2.1 异常与错误
  2. 2.2 检查型异常与非检查型异常
  3. 2.3 运行时异常和非运行时异常
  4. 2.4 异常的抛出
  5. 2.5 自定义异常
  6. 2.6 异常的处理(一)
  7. 2.7 异常的处理(二)
  8. 2.8 改错

2.1 异常与错误

简述 ErrorException 的区别。

2.2 检查型异常与非检查型异常

简述Java中的检查型异常与非检查型异常的区别,并通过程序案例触发检查型异常和非检查型异常。

1、简述两种异常的区别

2、 编写一个程序读取磁盘上的文件,并处理 FileNotFoundException 检查型异常。
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class TestFileNotFound {
    public static void main(String[] args) {
        File file = new File("test.txt");
        FileReader reader = null;
        try{
            reader = new FileReader(file);
            System.out.println("读取文件成功");
            int ch;
            while ((ch = reader.read()) != -1) {
                System.out.print((char) ch);
            }
            System.out.println("\n读取完成。");
        } catch (FileNotFoundException e) {
            System.out.println("文件未找到");
            System.out.println("异常:" + e.getMessage());
        } catch (IOException e) {
            System.out.println("IO异常:" + e.getMessage());
        }
    }
}

运行截图:

image-20251211193149545

3、 编写一个进行数组操作的程序,故意触发 ArrayIndexOutOfBoundsException 非检查型异常。
public class TestException {
    public static void main(String[] args) {
        int[] arr = {10, 20, 30};
        System.out.println("数组长度:" + arr.length);
        System.out.println("访问下标为0的元素:" + arr[0]);
        System.out.println("访问下标为3的元素:" + arr[3]);
        System.out.println("程序结束");
    }
}

运行截图:

image-20251211193106096

2.3 运行时异常和非运行时异常

简述运行时异常和非运行时异常的区别。

运行时异常就是非检查型异常,非运行时异常就是检查型异常。和上面那个题一样。

2.4 异常的抛出

简述Java异常处理中 throwthrows 关键字的区别。

2.5 自定义异常

见文件夹/code/5

2.6 异常的处理(一)

见文件夹/code/6

2.7 异常的处理(二)

见文件夹/code/7

2.8 改错

import java.io.IOException;

public class Main {
    public static void start() throws IOException, RuntimeException {
        throw new RuntimeException("Unable to Start");
    }

    public static void main(String[] args) {
        try {
            start();
        } catch (RuntimeException re) {
            re.printStackTrace();
        } catch (IOException ie) {
            ie.printStackTrace();
        }
    }
}

代码下载: lab06-code.zip