目录

  1. 什么是异常?
  2. Java 异常分类
  3. Java 异常的继承体系
  4. 异常处理机制(try-catch-finally)
  5. throws 关键字
  6. throw 关键字
  7. 自定义异常
  8. 多异常捕获与异常链
  9. 参考资料
  10. 出站链接

1. 什么是异常?

异常(Exception) 是 Java 运行时错误的表示,它指的是程序在执行过程中遇到的 不正常的事件,如 除零错误、数组越界、文件未找到、空指针 等。

Java 异常特性

  • 类(Class) 形式存在。
  • Throwable 类派生。
  • 可以使用 try-catch-finally 处理异常。
  • 支持 自定义异常

2. Java 异常分类

类别描述示例
受检异常(Checked Exception)编译时异常,必须显式处理IOException, SQLException
运行时异常(Unchecked Exception)运行时错误,可不显式处理NullPointerException, ArithmeticException
错误(Error)严重错误,无法恢复OutOfMemoryError, StackOverflowError

3. Java 异常的继承体系

java.lang.Throwable  
 ├── java.lang.Exception  
 │    ├── java.io.IOException  
 │    ├── java.sql.SQLException  
 │    ├── java.lang.ClassNotFoundException  
 │    └── ...  
 ├── java.lang.RuntimeException  
 │    ├── java.lang.NullPointerException  
 │    ├── java.lang.ArithmeticException  
 │    ├── java.lang.ArrayIndexOutOfBoundsException  
 │    ├── java.lang.IllegalArgumentException  
 │    └── ...  
 └── java.lang.Error  
      ├── java.lang.OutOfMemoryError  
      ├── java.lang.StackOverflowError  
      ├── java.lang.VirtualMachineError  
      └── ...


4. 异常处理机制(try-catch-finally)

4.1 try-catch 语句

public class ExceptionExample {
    public static void main(String[] args) {
        try {
            int result = 10 / 0;  // 可能抛出异常
        } catch (ArithmeticException e) {
            System.out.println("捕获到异常: " + e.getMessage());
        }
    }
}

4.2 try-catch-finally 语句

finally 块无论是否发生异常都会执行,用于资源释放。

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class FinallyExample {
    public static void main(String[] args) {
        Scanner scanner = null;
        try {
            scanner = new Scanner(new File("test.txt"));
        } catch (FileNotFoundException e) {
            System.out.println("文件未找到");
        } finally {
            if (scanner != null) {
                scanner.close();
                System.out.println("资源已关闭");
            }
        }
    }
}


5. throws 关键字

throws 关键字用于 方法声明,表示该方法可能抛出异常,调用者必须处理。

import java.io.FileNotFoundException;
import java.io.FileReader;

public class ThrowsExample {
    public static void readFile() throws FileNotFoundException {
        FileReader reader = new FileReader("test.txt");
    }

    public static void main(String[] args) {
        try {
            readFile();
        } catch (FileNotFoundException e) {
            System.out.println("文件未找到");
        }
    }
}


6. throw 关键字

throw 用于 主动抛出异常

public class ThrowExample {
    public static void checkAge(int age) {
        if (age < 18) {
            throw new IllegalArgumentException("年龄必须大于 18");
        }
        System.out.println("年龄符合要求");
    }

    public static void main(String[] args) {
        checkAge(16);  // 抛出异常
    }
}


7. 自定义异常

Java 允许继承 Exception 创建自定义异常类。

class CustomException extends Exception {
    public CustomException(String message) {
        super(message);
    }
}

public class CustomExceptionExample {
    public static void validate(int age) throws CustomException {
        if (age < 18) {
            throw new CustomException("未满 18 岁,禁止访问");
        }
    }

    public static void main(String[] args) {
        try {
            validate(16);
        } catch (CustomException e) {
            System.out.println("捕获到异常: " + e.getMessage());
        }
    }
}


8. 多异常捕获与异常链

8.1 多异常捕获(JDK 7+ 支持)

try {
    int result = 10 / 0;
    int[] arr = new int[3];
    arr[5] = 10;
} catch (ArithmeticException | ArrayIndexOutOfBoundsException e) {
    System.out.println("捕获异常: " + e.getMessage());
}

8.2 异常链(Exception Chaining)

class CustomException extends Exception {
    public CustomException(String message, Throwable cause) {
        super(message, cause);
    }
}

public class ExceptionChainExample {
    public static void main(String[] args) {
        try {
            throw new ArithmeticException("数学错误");
        } catch (ArithmeticException e) {
            throw new RuntimeException("包装异常", e);
        }
    }
}


9. 参考资料


10. 出站链接