蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

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

JAVAWindows x64、Eclipse Adoptium OpenJDK 1.8.0_492 (javac + java) 本地环境。ExploreExceptions.java
ExploreExceptions.java348 行
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());
    }
}
本例需在 Windows x64、Eclipse Adoptium OpenJDK 1.8.0_492 (javac + java) 本地环境。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows x64、Eclipse Adoptium OpenJDK 1.8.0_492 (javac + java) 本地环境。

入口文件:projects/java-exceptions-lab/ExploreExceptions.java

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 ExploreExceptions.java,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、Eclipse Adoptium OpenJDK 1.8.0_492 (javac + java) 本地环境。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:Java

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

下载课程关联工程包:Java

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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