According to the source of Closable.use
, if an error occurs, an exception will be thrown.
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
}
}
}
In most examples of Closable.use
, try-catch is not used as shown below.
Why isn't error handling needed? Is it safe?
BufferedReader(FileReader("test.file")).use { return it.readLine() }
use
which can throw the exception that I believe the OP is worried about.use
is like doing a traditional try/catch/finally. Putting it outside causes the exceptions to be handled after the object is closed. If the act of closing the object can itself throw an exception, then you need to catch that outsideuse
. This behavior is similar to Java's try-with-resources.use
works differently than Java'stry
-with-resources when it comes to stacked exceptions from both the virtualtry
andfinally
blocks.use
suppresses the exception fromclose
, buttry
-with-resources suppresses the exception fromtry
.