java - 可以捕获 Throwable 来执行清理吗?

标签 java try-catch finally throwable

<分区>

举个例子:

public List<CloseableThing> readThings(List<File> files) throws IOException {
    ImmutableList.Builder<CloseableThing> things = ImmutableList.builder();
    try {
        for (File file : files) {
            things.add(readThing(file))
        }
        return things.build();
    } catch (Throwable t) {
        for (CloseableThing thing : things.build()) {
            thing.close();
        }
        throw t;
    }
}

一个code review评论进来了,因为一般有规定不抓Throwable。进行这种仅失败清理的旧模式是:

public List<CloseableThing> readThings(List<File> files) throws IOException {
    ImmutableList.Builder<CloseableThing> things = ImmutableList.builder();
    boolean success = false;
    try {
        for (File file : files) {
            things.add(readThing(file))
        }
        success = true;
        return things.build();
    } finally {
        if (!success) {
            for (CloseableThing thing : things.build()) {
                thing.close();
            }
        }
    }
}

我觉得这有点乱,不完全理解它与捕获 Throwable 是否有任何不同。在任何一种情况下,异常都会传播。在任何一种情况下,当可能发生 OutOfMemoryError 时,都会运行其他代码。

那么最后真的更安全了吗?

最佳答案

ThrowableExceptionError 的父类型,所以捕获Throwable 意味着同时捕获这两个异常作为错误。 Exception 是你可以恢复的东西(比如 IOException),Error 是更严重的东西,通常你不能轻易恢复(比如 ClassNotFoundError)所以它不会捕获错误很有意义,除非您知道自己在做什么。

关于java - 可以捕获 Throwable 来执行清理吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17333925/

相关文章:

Java 处理 if null then new 的不同方法

flutter - flutter 一些异常未得到处理/捕获

java - 尝试使用多个 EditText 进行 Catch,并与 OnClick 进行交互

javascript - try-catch 和 async wait js 中的更改顺序?

java - 如果我在命令行中输入 Ctrl-C,Java 中的 finally block 还会执行吗?

python try-finally

java - 在处理 n 层时捕获调用堆栈高位的异常?

java - 当我的应用程序关闭时,当引用另一个类中的静态方法时,字符串在扩展 BroadcastReceiver 的类中返回 null

Java线程问题

java - 在生成 .equals() 时,有什么理由更喜欢 getClass() 而不是 instanceof?