gpt4 book ai didi

java - 处理(或抑制)AutoCloseable 抛出的异常的推荐方法是什么?

转载 作者:行者123 更新时间:2023-11-29 05:31:42 26 4
gpt4 key购买 nike

我正在升级一些现有的 API,这些 API 将 Iterable 设为 AutoCloseable 敏感。例如,给定:

/**
* @throws NoSuchElementException
*/
public static <T> T getOne(Iterable<T> iterable) {
return iterable.iterator().next();
}

如果迭代器是可关闭的,我想要关闭迭代器的方法。到目前为止,这是我得到的:

/**
* @throws NoSuchElementException
*/
public static <T> T getOne(Iterable<T> iterable) {
Iterator<T> iterator = iterable.iterator();
try {
return iterable.iterator().next();
} finally {
if (iterator instanceof AutoCloseable) {
try {
((AutoCloseable) iterator).close();
} catch (Exception ignored) {
// intentionally suppressed
}
}
}
}

鉴于 JDK 文档如何引用 Throwable.getSuppressed() ,这段代码应该做类似于以下的事情吗?

      } catch (Exception x) {
RuntimeException rte = new RuntimeException("Could not close iterator");
rte.addSuppressed(x);
throw rte;
}

最佳答案

我认为最好的做法是,如果你发现你有一个 AutoCloseable,那么简单地使用 try-with-resources 结构,就像这样:

/**
* @throws NoSuchElementException
*/
public static <T> T getOne(Iterable<T> iterable) {
Iterator<T> iterator = iterable.iterator();
if (iterator instanceof AutoCloseable) {
try (AutoCloseable c = (AutoCloseable) iterator) {
return iterator.next();
}
} else {
return iterator.next();
}
}

然后语言级构造将以正确的方式处理异常(包括在 close 方法中)。

关于java - 处理(或抑制)AutoCloseable 抛出的异常的推荐方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20863919/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com