Java 基础:异常处理 try/catch/finally

一、异常体系

Throwable 分两支:Error(系统级,如 OOM,一般不捕获)和 Exception。RuntimeException 是非受检异常(空指针、越界),其他 Exception 是受检异常(必须 try/catch 或 throws 声明)。

二、try/catch/finally

try {
    int x = 1 / 0;
} catch (ArithmeticException e) {
    System.out.println(e.getMessage());
} finally {
    System.out.println("无论是否异常都执行"); // 常用于关资源
}

三、try-with-resources

实现 AutoCloseable 的资源(如流、连接)用此语法自动关闭,免 finally:

try (BufferedReader br = new BufferedReader(...)) {
    return br.readLine();
} catch (IOException e) { ... }

四、自定义异常

class BizException extends RuntimeException {},便于业务层抛出语义化错误。不要在 catch 里吞掉异常(空 catch 是大忌)。