本文介绍了抓住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;
    }
}

代码审查评论来了,因为通常有一个规则不要抓住Throwable。进行此类仅故障清理的旧模式是:

A code review comment came in because there is generally a rule not to catch Throwable. The older pattern for doing this kind of failure-only cleanup was:

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();
            }
        }
    }
}

I发现这有点凌乱,并不完全了解它是否与捕捉Throwable有任何不同。在任何一种情况下,异常都会传播。在任何一种情况下,当可能发生OutOfMemoryError时,正在运行其他代码。

I find this a bit messy and don't fully understand whether it's any different from catching the Throwable. In either case, the exception propagates. In either case, additional code is being run when potentially an OutOfMemoryError might have occurred.

所以最终真的更安全吗?

So is finally really any safer?

推荐答案

Throwable 例外错误的父类型,因此抓住 Throwable 意味着同时捕获异常和错误。异常是你可以恢复的东西(比如 IOException ),错误是更严重的,通常你不能轻易恢复(比如 ClassNotFoundError )所以它不会除非你知道自己在做什么,否则很难理解错误

Throwable is the parent type of Exception and Error, so catching Throwable means catching both Exceptions as well as Errors. An Exception is something you could recover (like IOException), an Error is something more serious and usually you could'nt recover easily (like ClassNotFoundError) so it doesn't make much sense to catch an Error unless you know what you're doing.

这篇关于抓住Throwable进行清理是否可以?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-11 17:14