Pedro González
05/03/2020, 3:12 AMDerek Peirce
05/03/2020, 5:25 AMpublic 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
}
}
}
}
Are you sure? Here's how use
is written in the stdlib I'm using, and it looks like the exception is rethrown correctly, the only issue is that any exceptions on closing aren't included for whatever reason.bod
05/03/2020, 7:39 AMDominaezzz
05/03/2020, 2:21 PMapiVersionIsAtLeast
is for backwords compat I think.Pedro González
05/03/2020, 2:45 PMtry{ use(myresource) }
catch(e: SomeException) { handleCustom(e) }
to catch a specific type of exception, or rather
try{ use(myresource) }
catch(e: SomeException) {
when(val it = e) {
is MyException -> handleCustom(e)
else -> {}
}
}
Pedro González
05/03/2020, 2:46 PMDominaezzz
05/03/2020, 2:48 PMPedro González
05/03/2020, 2:49 PM