蓝色天空.知识 · 实践 · 创造
我的收藏
Java 教程目录 57章
Java / LEARN BY DOING

Java 异常处理

全面梳理 Java 异常分类与 Throwable 层次体系、常见内置受检与非受检异常、try-catch-finally、Java 7 多异常合并与 try-with-resources 自动资源管理及自定义异常实践。

学完这一章,你能够

  • 全面梳理 Java 异常分类与 Throwable 层次体系、常见内置受检与非受检异常、try-catch-finally、Java 7 多异常合并与 try-with-resources 自动资源管理及自定义异常实践。

异常的成因、三大分类与核心关键字

异常处理用于应对程序运行期间偏离正常流程的故障,例如用户输入非法数据、目标文件不存在、网络连接中断或虚拟机内存耗尽等。需要区分编译期语法错误与运行期异常:源码遗漏分号属于编译器(`javac`)直接拦截的语法错误,而非运行时抛出 `java.lang.Error`;而执行整数除零 `11 / 0` 则会在运行时抛出 `java.lang.ArithmeticException`。

Java 将异常与错误事件划分为三大类:其一是受检异常(Checked Exception),通常源自外部环境或 I/O 问题(如打开不存在的文件),编译器强制要求使用 `try-catch` 捕获或用 `throws` 向上声明;其二是运行时异常(RuntimeException 及其子类,又称非受检异常),如 `NullPointerException`、`ArrayIndexOutOfBoundsException`,通常源于程序逻辑缺陷,编译期不强制捕获;其三是 `Error`(如栈溢出 `StackOverflowError`),代表脱离应用正常恢复能力的严重底层故障。

Java 围绕异常处理提供了五个核心关键字与基类:`try` 包裹受保护代码,`catch` 声明并处理匹配的异常类型,`finally` 放置无论是否抛出异常都需执行的清理逻辑,`throw` 在语句中主动抛出异常实例,`throws` 在方法签名中声明可能向外传播的异常类型;`Exception` 继承自 `Throwable`,提供了 `getMessage()`、`printStackTrace()` 等常用诊断方法。

Throwable 层次体系与内置异常类

所有异常与错误都继承自根类 `java.lang.Throwable`,其下分为 `Error` 与 `Exception` 两大分支。`Error` 指示虚拟机或运行时环境的严重故障(如内存溢出),常规业务代码不应吞掉或尝试从中恢复;`Exception` 则包含 `IOException` 等受检异常家族与 `RuntimeException` 非受检异常家族。本站实测验证了 `Throwable` 对 `Exception`、`Error` 以及 `Exception` 对 `RuntimeException`、`IOException` 的继承关系。

`java.lang` 包默认导入所有 Java 源文件,因此其中定义的大多数常见非受检异常(如 `ArithmeticException`、`NullPointerException`、`NumberFormatException` 等 15 种)与受检异常(如 `ClassNotFoundException`、`NoSuchMethodException` 等 7 种)均可直接使用;而 `Throwable` 提供了 6 个核心方法用于读取错误消息、原因链、堆栈轨迹及打印调用回溯。下表完整汇总这三组内置参考。

try-catch 捕获、多重捕获与 Java 7 多异常合并

将可能发生异常的语句放入 `try` 块,并在其后紧跟 `catch (异常类型 变量)` 即可拦截并处理异常。当访问长度为 2 的数组下标 `a[3]` 时,JVM 会构造 `ArrayIndexOutOfBoundsException` 实例并按顺序匹配 `catch` 参数,处理完成后程序继续执行 `try-catch` 之后的语句而不至于异常终止。

一个 `try` 块后面可以连接任意多个 `catch` 块构成多重捕获。JVM 会自上而下依次比对异常类型,命中首个兼容的 `catch` 后即不再进入后续分支。因此必须将更具体的子类异常放在父类异常之前——例如先捕获 `FileNotFoundException` 再捕获 `IOException` 是合法且标准的顺序(反之将 `IOException` 置于前面才会导致子类分支不可达而编译报错)。

从 Java 7 起,可使用竖线 `|` 在单个 `catch` 子句中合并捕获多个互无继承关系的异常(如 `catch (SQLException | IOException e)`)。合并捕获时要求各异常类型不得存在父子继承关系(否则如 `FileNotFoundException | IOException` 会直接编译报错),异常变量 `e` 隐式为 `final` 且静态类型推断为它们的最近公共父类,因此块内只能调用公共父类定义的方法。本站实测确认 `SQLException` 与 `IOException` 均能被同一合并 `catch` 块准确捕获。

throw/throws、finally 与 try-with-resources

`throw` 与 `throws` 分工明确:`throw` 写在方法体内用于立即抛出一个具体异常对象(如参数小于 0 时 `throw new IllegalArgumentException(...)`);`throws` 写在方法声明尾部,以逗号分隔列出该方法不自行处理而交由调用方处理的受检异常(如 `throws IOException` 或 `throws RemoteException, InsufficientFundsException`)。

`finally` 块位于 `try`/`catch` 之后,无论受保护代码是否抛出异常,其中的清理逻辑总会执行(除非 JVM 强制退出)。语法上需遵守四条规则:`catch` 不能脱离 `try` 单独存在;`finally` 在 `try-catch` 后并非强制;普通 `try` 之后至少需要 `catch` 或 `finally` 之一;`try`、`catch`、`finally` 之间不能插入其他语句。本站实测在捕获数组越界后,`finally` 仍稳定将 `arr[0]` 赋值为 `6`。

JDK 7 新增的 `try-with-resources` 语句专门用于自动关闭实现了 `AutoCloseable` 接口的资源(如 `BufferedReader`、`Scanner`、`PrintWriter`)。相比手写嵌套 `try-catch-finally` 并逐个判空调用 `close()`,`try-with-resources` 不仅大幅精简代码,还能在主逻辑与关闭阶段同时抛异常时保留主异常并将关闭异常挂入 suppressed 列表。

在 `try (...)` 圆括号中可用分号 `;` 同时声明多个资源,退出代码块时 JVM 会严格按照声明的**相反顺序**自动关闭它们(后声明先关闭)。本站实验使用两个自定义 `TrackedResource` 实测,确认日志顺序为 `["body", "close:second", "close:first"]`,同时验证了 `BufferedReader` 读取临时文件后自动释放句柄。

自定义异常、来源归类与最佳实践

业务系统常通过继承 `Exception`(定义受检异常)或 `RuntimeException`(定义非受检异常)来表达领域错误,自定义异常类与普通类一样可以携带业务字段和访问方法。本站复现银行账户场景:定义携带缺口金额的 `InsufficientFundsException` 与 `CheckingAccount`,实测存入 `500.0`、取出 `100.0` 后余额为 `400.0`,再尝试取出 `600.0` 时精确抛出异常并报告缺口 `200.0`。

按抛出主体可将常见异常分为 JVM 异常(如 `NullPointerException`、`ArrayIndexOutOfBoundsException`、`ClassCastException`)与程序/API 显式抛出的异常(如 `IllegalArgumentException`、`IllegalStateException`)。工程实践中应在具备恢复上下文的层级精确捕获特定异常、避免宽泛吞掉 `Exception`、优先用 `try-with-resources` 或 `finally` 释放外部资源,并谨慎对待受检异常的转换与传播。

java.lang 常见非受检异常(RuntimeException 子类)

异常类名触发场景说明
ArithmeticException算术运算条件异常时抛出,典型如整数除以零。
ArrayIndexOutOfBoundsException使用负数或大于等于数组长度的非法下标访问数组时抛出。
ArrayStoreException向对象数组存入与数组实际元素类型不兼容的对象时抛出。
ClassCastException将对象强制转换为非其实例类型(或非其父类型)时抛出。
IllegalArgumentException调用方传入了不合法或不满足前置条件的参数值时抛出。
IllegalMonitorStateException当前线程未持有对象监视器锁却调用 wait()/notify() 时抛出。
IllegalStateException对象或运行环境当前不处于所请求操作允许的状态时抛出。
IllegalThreadStateException线程生命周期状态不满足目标操作要求(如重复 start())时抛出。
IndexOutOfBoundsException数组、字符串或集合等索引访问超出有效范围时的通用父类异常。
NegativeArraySizeException试图创建长度为负数的数组时抛出。
NullPointerException对 null 引用解引用(调用方法、访问字段或数组长度)时抛出。
NumberFormatException将格式非法的字符串解析为数值类型(如 Integer.parseInt)时抛出。
SecurityException安全策略检查拒绝当前敏感操作时由安全管理器抛出。
StringIndexOutOfBoundsException访问字符串字符或子串时索引为负或越界抛出。
UnsupportedOperationException调用对象不支持的操作(例如修改不可变集合)时抛出。

java.lang 常见受检异常(Checked Exception)

异常类名触发场景说明
ClassNotFoundException按名称动态加载类(如 Class.forName)但在类路径中找不到该类时抛出。
CloneNotSupportedException调用 Object.clone() 但目标类未实现 Cloneable 标记接口时抛出。
IllegalAccessException反射访问或实例化超出访问权限控制范围的类或成员时抛出。
InstantiationException尝试反射实例化抽象类、接口或缺少无参构造方法的类型时抛出。
InterruptedException线程处于等待、休眠或阻塞状态时被其他线程中断而抛出。
NoSuchFieldException通过反射按名称查找类中不存在的字段时抛出。
NoSuchMethodException通过反射按名称与参数列表查找不存在的方法时抛出。

Throwable 类核心诊断方法

序号方法签名与作用
1public String getMessage():返回构造异常时传入的详细错误消息字符串(未提供时为 null)。
2public Throwable getCause():返回引发当前异常的底层原因异常对象(无原因链时为 null)。
3public String toString():返回异常全限定类名与消息拼装的简短描述。
4public void printStackTrace():将异常信息及调用栈回溯输出到标准错误流(或重载传入的 PrintWriter/PrintStream)。
5public StackTraceElement[] getStackTrace():返回表示调用栈帧的数组,索引 0 为最顶层异常发生点,末尾为调用入口。
6public Throwable fillInStackTrace():以当前执行位置的调用栈刷新异常堆栈轨迹并返回自身引用。

验证 try-catch-finally、多重与合并捕获、try-with-resources 逆序关闭及自定义银行异常

含完整源码 · 348 行
展开查看收起
java
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class ExploreExceptions {

    static class CaseResult {
        final String name;
        final String summary;
        final String expectedJson;
        final String actualJson;
        final boolean passed;

        CaseResult(String name, String summary, String expectedJson, String actualJson) {
            this.name = name;
            this.summary = summary;
            this.expectedJson = expectedJson;
            this.actualJson = actualJson;
            this.passed = expectedJson.equals(actualJson);
        }
    }

    static String esc(String s) {
        if (s == null) return "null";
        StringBuilder sb = new StringBuilder("\"");
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            switch (c) {
                case '"': sb.append("\\\""); break;
                case '\\': sb.append("\\\\"); break;
                case '\b': sb.append("\\b"); break;
                case '\f': sb.append("\\f"); break;
                case '\n': sb.append("\\n"); break;
                case '\r': sb.append("\\r"); break;
                case '\t': sb.append("\\t"); break;
                default:
                    if (c < 0x20) sb.append(String.format("\\u%04x", (int) c));
                    else sb.append(c);
            }
        }
        sb.append("\"");
        return sb.toString();
    }

    static String listJson(List<String> items) {
        StringBuilder sb = new StringBuilder("[");
        for (int i = 0; i < items.size(); i++) {
            if (i > 0) sb.append(", ");
            sb.append(esc(items.get(i)));
        }
        sb.append("]");
        return sb.toString();
    }

    static class InsufficientFundsException extends Exception {
        private final double amount;

        InsufficientFundsException(double amount) {
            super("Short by " + amount);
            this.amount = amount;
        }

        double getAmount() {
            return amount;
        }
    }

    static class CheckingAccount {
        private double balance;
        private final int number;

        CheckingAccount(int number) {
            this.number = number;
        }

        void deposit(double amount) {
            balance += amount;
        }

        void withdraw(double amount) throws InsufficientFundsException {
            if (amount <= balance) {
                balance -= amount;
            } else {
                throw new InsufficientFundsException(amount - balance);
            }
        }

        double getBalance() {
            return balance;
        }

        int getNumber() {
            return number;
        }
    }

    static class TrackedResource implements AutoCloseable {
        private final String id;
        private final List<String> log;

        TrackedResource(String id, List<String> log) {
            this.id = id;
            this.log = log;
        }

        @Override
        public void close() {
            log.add("close:" + id);
        }
    }

    static class NonCloneableSample {
        Object tryClone() throws CloneNotSupportedException {
            return super.clone();
        }
    }

    static abstract class AbstractSample {}

    static void checkPositive(int num) {
        if (num < 0) {
            throw new IllegalArgumentException("Number must be positive");
        }
    }

    static void multiThrows(int mode) throws IOException, SQLException {
        if (mode == 1) throw new IOException("io-boom");
        if (mode == 2) throw new SQLException("sql-boom");
    }

    static CaseResult testTryCatchAndFinally() {
        int[] arr = new int[2];
        String caughtType = "";
        boolean finallyRan = false;
        try {
            int x = arr[3];
            caughtType = "unexpected:" + x;
        } catch (ArrayIndexOutOfBoundsException e) {
            caughtType = e.getClass().getSimpleName() + ":" + e.getMessage();
        } finally {
            arr[0] = 6;
            finallyRan = true;
        }
        String expected = "{\"caught\": \"ArrayIndexOutOfBoundsException:3\", \"arr0\": 6, \"finallyRan\": true}";
        String actual = "{\"caught\": " + esc(caughtType) + ", \"arr0\": " + arr[0] + ", \"finallyRan\": " + finallyRan + "}";
        return new CaseResult(
            "try_catch_and_finally",
            "验证越界触发 ArrayIndexOutOfBoundsException 并由 catch 捕获,且 finally 块始终执行收尾赋值",
            expected,
            actual
        );
    }

    static CaseResult testMultipleCatchAndHierarchy() {
        List<String> branches = new ArrayList<>();
        for (int mode = 0; mode < 2; mode++) {
            try {
                if (mode == 0) throw new FileNotFoundException("missing.txt");
                throw new IOException("generic-io");
            } catch (FileNotFoundException e) {
                branches.add("fnf:" + e.getMessage());
            } catch (IOException e) {
                branches.add("io:" + e.getMessage());
            }
        }
        boolean hierarchyOk = Throwable.class.isAssignableFrom(Exception.class)
            && Throwable.class.isAssignableFrom(Error.class)
            && Exception.class.isAssignableFrom(RuntimeException.class)
            && Exception.class.isAssignableFrom(IOException.class)
            && !RuntimeException.class.isAssignableFrom(IOException.class);
        String expected = "{\"branches\": [\"fnf:missing.txt\", \"io:generic-io\"], \"hierarchyOk\": true}";
        String actual = "{\"branches\": " + listJson(branches) + ", \"hierarchyOk\": " + hierarchyOk + "}";
        return new CaseResult(
            "multiple_catch_and_hierarchy",
            "验证多重 catch 按子类到父类匹配以及 Throwable -> Exception/Error 与 RuntimeException/IOException 层次关系",
            expected,
            actual
        );
    }

    static CaseResult testMultiCatchJava7() {
        List<String> caught = new ArrayList<>();
        for (int mode : new int[]{1, 2}) {
            try {
                multiThrows(mode);
            } catch (SQLException | IOException e) {
                caught.add(e.getClass().getSimpleName() + ":" + e.getMessage());
            }
        }
        String expected = "[\"IOException:io-boom\", \"SQLException:sql-boom\"]";
        String actual = listJson(caught);
        return new CaseResult(
            "multi_catch_java7",
            "验证 Java 7 多异常合并捕获 catch (SQLException | IOException e) 统一处理无继承关系的受检异常",
            expected,
            actual
        );
    }

    static CaseResult testThrowAndThrows() {
        String argMsg = "";
        try {
            checkPositive(-5);
        } catch (IllegalArgumentException e) {
            argMsg = e.getMessage();
        }
        checkPositive(10);
        String propagated = "";
        try {
            multiThrows(1);
        } catch (IOException | SQLException e) {
            propagated = e.getClass().getSimpleName();
        }
        String expected = "{\"illegalArg\": \"Number must be positive\", \"propagated\": \"IOException\"}";
        String actual = "{\"illegalArg\": " + esc(argMsg) + ", \"propagated\": " + esc(propagated) + "}";
        return new CaseResult(
            "throw_and_throws",
            "验证 throw 主动抛出参数校验异常与 throws 向调用方声明传播多个受检异常",
            expected,
            actual
        );
    }

    static CaseResult testTryWithResourcesOrder() throws Exception {
        List<String> closeLog = new ArrayList<>();
        try (TrackedResource first = new TrackedResource("first", closeLog);
             TrackedResource second = new TrackedResource("second", closeLog)) {
            closeLog.add("body");
        }
        Path tmp = Files.createTempFile("twr-demo-", ".txt");
        String firstLine;
        try {
            Files.write(tmp, "hello-twr\n".getBytes(StandardCharsets.UTF_8));
            try (BufferedReader br = new BufferedReader(new FileReader(tmp.toFile()))) {
                firstLine = br.readLine();
            }
        } finally {
            Files.deleteIfExists(tmp);
        }
        String expected = "{\"closeOrder\": [\"body\", \"close:second\", \"close:first\"], \"readLine\": \"hello-twr\"}";
        String actual = "{\"closeOrder\": " + listJson(closeLog) + ", \"readLine\": " + esc(firstLine) + "}";
        return new CaseResult(
            "try_with_resources_order",
            "验证 try-with-resources 自动关闭单个文件流,以及多资源按声明逆序关闭(后声明先关闭)",
            expected,
            actual
        );
    }

    static CaseResult testCustomExceptionBank() {
        CheckingAccount acc = new CheckingAccount(101);
        acc.deposit(500.0);
        double afterFirst = 0.0;
        double shortage = 0.0;
        try {
            acc.withdraw(100.0);
            afterFirst = acc.getBalance();
            acc.withdraw(600.0);
        } catch (InsufficientFundsException e) {
            shortage = e.getAmount();
        }
        String expected = "{\"account\": 101, \"balanceAfter100\": 400.0, \"shortage\": 200.0}";
        String actual = "{\"account\": " + acc.getNumber() + ", \"balanceAfter100\": " + afterFirst + ", \"shortage\": " + shortage + "}";
        return new CaseResult(
            "custom_exception_bank",
            "验证自定义受检异常 InsufficientFundsException 与 CheckingAccount 存款取款余额不足场景",
            expected,
            actual
        );
    }

    static CaseResult testBuiltinExceptionsAndThrowableApi() {
        List<String> unchecked = new ArrayList<>();
        try { int x = 11 / 0; unchecked.add("" + x); } catch (ArithmeticException e) { unchecked.add(e.getClass().getSimpleName()); }
        try { String s = null; unchecked.add("" + s.length()); } catch (NullPointerException e) { unchecked.add(e.getClass().getSimpleName()); }
        try { Integer.parseInt("abc"); } catch (NumberFormatException e) { unchecked.add(e.getClass().getSimpleName()); }
        try { Object o = "txt"; Integer n = (Integer) o; unchecked.add("" + n); } catch (ClassCastException e) { unchecked.add(e.getClass().getSimpleName()); }
        try { int[] neg = new int[-1]; unchecked.add("" + neg.length); } catch (NegativeArraySizeException e) { unchecked.add(e.getClass().getSimpleName()); }
        try { "ab".charAt(5); } catch (StringIndexOutOfBoundsException e) { unchecked.add(e.getClass().getSimpleName()); }
        try { Object[] oa = new String[1]; oa[0] = 42; } catch (ArrayStoreException e) { unchecked.add(e.getClass().getSimpleName()); }
        try { Collections.emptyList().add("x"); } catch (UnsupportedOperationException e) { unchecked.add(e.getClass().getSimpleName()); }

        List<String> checked = new ArrayList<>();
        try { Class.forName("no.such.DemoClass"); } catch (ClassNotFoundException e) { checked.add(e.getClass().getSimpleName()); }
        try { new NonCloneableSample().tryClone(); } catch (CloneNotSupportedException e) { checked.add(e.getClass().getSimpleName()); }
        try { AbstractSample.class.newInstance(); } catch (InstantiationException | IllegalAccessException e) { checked.add(e.getClass().getSimpleName()); }
        try { String.class.getDeclaredField("noSuchField"); } catch (NoSuchFieldException e) { checked.add(e.getClass().getSimpleName()); }
        try { String.class.getDeclaredMethod("noSuchMethod"); } catch (NoSuchMethodException e) { checked.add(e.getClass().getSimpleName()); }

        Throwable root = new IllegalStateException("root-state");
        Exception wrapped = new Exception("outer-msg", root);
        StringWriter sw = new StringWriter();
        wrapped.printStackTrace(new PrintWriter(sw));
        boolean apiOk = "outer-msg".equals(wrapped.getMessage())
            && wrapped.getCause() == root
            && wrapped.toString().equals("java.lang.Exception: outer-msg")
            && wrapped.getStackTrace().length > 0
            && wrapped.fillInStackTrace() == wrapped
            && sw.toString().contains("outer-msg");

        String expected = "{\"uncheckedCount\": 8, \"checkedCount\": 5, \"throwableApiOk\": true}";
        String actual = "{\"uncheckedCount\": " + unchecked.size() + ", \"checkedCount\": " + checked.size() + ", \"throwableApiOk\": " + apiOk + "}";
        return new CaseResult(
            "builtin_exceptions_and_throwable_api",
            "验证 java.lang 常见非受检与受检内置异常触发以及 Throwable 六项核心诊断方法行为",
            expected,
            actual
        );
    }

    public static void main(String[] args) throws Exception {
        List<CaseResult> cases = Arrays.asList(
            testTryCatchAndFinally(),
            testMultipleCatchAndHierarchy(),
            testMultiCatchJava7(),
            testThrowAndThrows(),
            testTryWithResourcesOrder(),
            testCustomExceptionBank(),
            testBuiltinExceptionsAndThrowableApi()
        );
        StringBuilder out = new StringBuilder();
        out.append("{\"version\": ").append(esc(System.getProperty("java.version"))).append(", \"cases\": [");
        for (int i = 0; i < cases.size(); i++) {
            CaseResult c = cases.get(i);
            if (i > 0) out.append(", ");
            out.append("{\"name\": ").append(esc(c.name))
               .append(", \"summary\": ").append(esc(c.summary))
               .append(", \"expected\": ").append(c.expectedJson)
               .append(", \"actual\": ").append(c.actualJson)
               .append(", \"passed\": ").append(c.passed)
               .append("}");
        }
        out.append("]}");
        System.out.println(out.toString());
    }
}
在本地 OpenJDK 1.8.0_492 中离线通过 7 项异常处理实测,涵盖越界与 finally 必执行、层次校验、Java 7 多异常合并、多资源逆序关闭、InsufficientFundsException 及内置受检/非受检异常与 Throwable API。

查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载本章实验包 (mbskycom202612a1118.zip) ↓ 查看运行说明 ↗

本章附件与实例包

下载课程关联工程包:Java

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1118.zip

下载课程关联工程包:Java

课程关联工程包(登记关联57章) · 含当前章节或实例 · mbskycom202612a1104.zip

常见错误与边界检查

  • 实际端口、文档资源与应用配置都应和测试条件一致。

技术规范与官方资料

练习与参考解答

查看参考解答

如果 A 是 B 的子类,捕获 B 本身就已经覆盖了 A,同时列出二者属于冗余且语义冲突的声明,因此编译器直接报错;需要区别处理父子异常时应拆分为两个独立 catch 块并把子类放在前面。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习