I understand the kotlin "equivalent" of java's try...
# stdlib
p
I understand the kotlin "equivalent" of java's try-with-resources is the use() library function However, if exceptions occurs, use will just fail silently. Is there any alternative function/idiom that allows to manage exceptions explicitly without having to manually close the used resource?
d
Copy code
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
                }
        }
    }
}
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.
b
What do you mean by "not included"? The code looks correct to me (appart from the apiVersionAtLast business I have no idea what it is about)
d
apiVersionIsAtLeast
is for backwords compat I think.
p
Oh, I was misinformed then. So I need to use
Copy code
try{ use(myresource) }    
catch(e: SomeException) { handleCustom(e) }
to catch a specific type of exception, or rather
Copy code
try{ use(myresource) }    
catch(e: SomeException) { 
    when(val it = e) {
        is MyException -> handleCustom(e)
        else -> {}
    }
}
(btw why is slack not formatting my text? I thought ``` ``` created a code block)
d
Are you on a phone? Slack broke changed how it handles text. If your message isn't formatted before sending, it won't be.
p
Yup, that must be it then.