JP
07/13/2020, 12:39 PMtry-with-resources construct in Java to Kotlin, regarding handling exceptions?
// Java
DataSource ds = createDataSource();
try (Connection connection = ds.getConnection()) {
// ...
// just throw exception for simulation
throw new IllegalStateException()
// ...
} catch (SQLException e) {
e.printStackTrace()
}
I’ve tried to use the use function like this:
// Kotlin
val ds: DataSource = createDataSource()
try {
dataSource.connection.use { connection ->
// just throw exception for simulation
throw IllegalStateException()
}
} catch (e: SQLException) {
e.printStackTrace()
}
But SQLException is not caught, instead, only IllegalStateException could be caught.
How could one catch a SQLException thrown from java.sql.Connection.getConnection() gracefully using Kotlin, while, if possible, utilizing the use function to close the connection?asad.awadia
07/13/2020, 1:58 PMJP
07/14/2020, 6:55 AMlouiscad
07/14/2020, 7:11 AMSQLException, then throw a SQLException, not something else.jbnizet
07/14/2020, 9:13 AMimport java.sql.SQLException
class Connection : AutoCloseable {
override fun close() {
}
}
class DataSource {
val connection: Connection
get() {
throw SQLException("Ooops")
}
}
fun createDataSource() = DataSource()
fun main() {
val ds: DataSource = createDataSource()
try {
ds.connection.use { connection ->
// just throw exception for simulation
throw IllegalStateException()
}
} catch (e: SQLException) {
println("Caught SQLException")
e.printStackTrace()
}
}JP
07/14/2020, 12:10 PMtry/catch block outside the use block, and also use another try/catch block inside the use block for example, in case of executing rollback before the AutoClosable resource is closed by the use block? Or is there a more concise way to handle it?