【发布时间】:2020-09-21 03:55:59
【问题描述】:
根据Closable.use的来源,如果发生错误,会抛出异常。
public inline fun <T : Closeable?, R> T.use(block: (T) -> R): R {
var exception: Throwable? = null
try {
return block(this)
} catch (e: Throwable) {
exception = e
throw e
} finally {
when {
apiVersionIsAtLeast(1, 1, 0) -> this.closeFinally(exception)
this == null -> {}
exception == null -> close()
else ->
try {
close()
} catch (closeException: Throwable) {
// cause.addSuppressed(closeException) // ignored here
}
}
}
在Closable.use 的大多数示例中,不使用try-catch,如下所示。
为什么不需要错误处理?安全吗?
BufferedReader(FileReader("test.file")).use { return it.readLine() }
【问题讨论】:
-
本问答适用于 Java,但同样的概念也适用于 Kotlin:When to catch the Exception vs When to throw the Exceptions?。
-
@Tenfour04 try/catch 不应该包含使用函数吗?
-
@Tenfour04 @Tenfour04
use可以抛出我认为 OP 担心的异常。 -
将 try/catch 放入
use就像做传统的 try/catch/finally 一样。将其放在外面会导致在对象关闭之后处理异常。如果关闭对象的行为本身会引发异常,那么您需要在use之外捕获它。这种行为类似于 Java 的 try-with-resources。 -
有趣的是,
use在处理来自虚拟try和finally块的堆叠异常时与 Java 的try-with-resources 不同。use抑制来自close的异常,但try-with-resources 抑制来自try的异常。
标签: kotlin