User12322341232142
User12322341232142

Reputation: 103

Customize error message using Kotlin's use instead of try catch

I'm still learning Kotlin and I just learned about the "use" and how it is a replacement for a try, catch and finally block. However I am curious if it is possible to customize it's exception handling for example:

var connection: Connection? = null
try {
    connection = dataSource.connection
    connection.prepareStatement(query).execute()
} catch (e: SQLException) {
    logger.log("Specific error for that query")
    e.printStackTrace()
} finally {
    if (connection != null && !connection.isClosed) {
        connection.close()
    }
}

That code is my current one, I have a specific error I would like to display on the catch, would that be possible using use? This is my current use code:

dataSource.connection.use { connection ->
    connection.prepareStatement(query).execute()
}

Upvotes: 0

Views: 1271

Answers (1)

user2340612
user2340612

Reputation: 10743

As commented by @Tenfour04, and from the documentation

[use] Executes the given block function on this resource and then closes it down correctly whether an exception is thrown or not.

In particular it is implemented like this:

public inline fun <T : AutoCloseable?, R> T.use(block: (T) -> R): R {
    var exception: Throwable? = null
    try {
        return block(this)
    } catch (e: Throwable) {
        exception = e
        throw e
    } finally {
        this.closeFinally(exception)
    }
}

That piece of code should look familiar if you're a Java developer, but basically it executes block passing this (i.e. the receiver object) as an argument to your block of code. At the end it closes the AutoCloseable resource. If at any point an exception is thrown (either inside block or while closing the resource), that exception is thrown back to the caller, i.e. your code.

As an edge case you could have 2 exceptions, one when executing block and one when closing the resource. This is handled by closeFinally (whose source is available in the same file linked above) and the exception thrown while closing the resource is added as a suppressed exception to the one thrown from block – that's because only up to 1 exception can be thrown by a method, so they had to choose which one to throw. The same actually applies to the try-with-resources statement in Java.

Upvotes: 3

Related Questions