优秀的编程知识分享平台

网站首页 > 技术文章 正文

举例说明被抑制异常?(抑制过程的优势)

nanyue 2025-01-29 17:19:16 技术文章 9 ℃

在Java中,如果一个异常在另一个异常被抛出时被“抑制”,那么它可以通过Throwable.getSuppressed()方法被检索到。以下是一个例子,展示了如何创建一个被抑制的异常:

public class SuppressedExceptionExample {
    public static void main(String[] args) {
        try {
            // 开启资源
            AutoCloseable resource1 = new Resource1();
            AutoCloseable resource2 = new Resource2();

            // 假设这里发生了异常
            throw new Exception("Something went wrong!");

        } catch (Exception e) {
            // 捕获异常
            System.out.println("Caught main exception: " + e.getMessage());

            // 关闭资源并处理可能抛出的异常
            try {
                resource1.close();
            } catch (Exception closeException) {
                // 抑制关闭资源时抛出的异常
                e.addSuppressed(closeException);
            }

            try {
                resource2.close();
            } catch (Exception closeException) {
                // 抑制关闭资源时抛出的异常
                e.addSuppressed(closeException);
            }

            // 打印被抑制的异常
            for (Throwable suppressed : e.getSuppressed()) {
                System.out.println("Suppressed exception: " + suppressed.getMessage());
            }
        }
    }

    // 假设的资源类
    static class Resource1 implements AutoCloseable {
        @Override
        public void close() throws Exception {
            throw new Exception("Resource1 close failed!");
        }
    }

    static class Resource2 implements AutoCloseable {
        @Override
        public void close() throws Exception {
            throw new Exception("Resource2 close failed!");
        }
    }
}

在这个例子中,我们创建了两个实现了AutoCloseable接口的资源类Resource1和Resource2。在main方法中,我们尝试使用这些资源,并故意抛出一个异常。在catch块中,我们尝试关闭这些资源,并且捕获并抑制了在关闭资源时抛出的异常。

如果在关闭资源时抛出了异常,我们会使用Exception.addSuppressed()方法将这些异常添加到捕获的异常e的抑制列表中。然后,我们通过调用e.getSuppressed()方法来检索并打印出所有被抑制的异常。

当运行这个程序时,你会看到以下输出:

Caught main exception: Something went wrong!
Suppressed exception: Resource1 close failed!
Suppressed exception: Resource2 close failed!

这表明了主异常被捕获,并且在关闭资源时抛出的异常被成功抑制,并且可以通过getSuppressed()方法检索到。

#头条开新年##许愿赢现金##年终刮刮乐#

最近发表
标签列表