异常处理

Java 教程 · 第 6 章 · 7 次浏览

程序运行难免出错:除数为零、数组越界、文件不存在、网络断开。Java 用异常机制处理这些情况,让程序不至于直接崩溃。

异常体系

Throwable 是顶层,分两大类:Error(系统级错误,一般不处理)和 Exception(程序异常)。Exception 又分检查异常(编译器要求处理,如 IO)和运行时异常(如数组越界)。

try-catch-finally

try 放可能出错的代码;catch 捕获异常处理;finally 无论是否异常都执行(如关闭资源)。

抛出异常

方法里用 throw new Exception("消息") 主动抛;方法签名加 throws 声明可能抛出的异常。

代码示例

public class ExceptionDemo {
    public static void main(String[] args) {
        try {
            int result = divide(10, 0);
            System.out.println(result);
        } catch (ArithmeticException e) {
            System.out.println("数学错误:" + e.getMessage());
        } finally {
            System.out.println("总会执行(释放资源)");
        }

        try {
            int[] arr = {1, 2};
            System.out.println(arr[5]);
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("数组越界:" + e.getMessage());
        }
    }

    static int divide(int a, int b) {
        if (b == 0) throw new ArithmeticException("除数不能为 0");
        return a / b;
    }
}