Correct handled of try catch with nullabilty


#1

Hi everybody

I’m new in Kotlin, and I’m designing my first app with this language, now understand how to implements nullability feature. But I have a problem to understand how to write this code in kotlin:

>     public List<Task> getAllTasks(){
>         String sql =
>             "SELECT id, description, duedate " +
>             "FROM tasks";

>         try(Connection con = sql2o.open()) {
>             return con.createQuery(sql).executeAndFetch(Task.class);
>         }
>     }

well, I want handled the exception like this:

> public List<Task> getAllTasks(){
>     String sql =
>         "SELECT id, description, duedate " +
>         "FROM tasks";
>       Connection con = sql2o.open();
>       List<Task> tasks;

>     try {
>         tasks = con.createQuery(sql).executeAndFetch(Task.class);
>     } catch (Exception e){
>               logger.error("Error",e);
>     }

>     return tasks;
> }

What the best form to write this in kotlin?


#2

What do you want your method to return in case of an exception?


#3

I was thinking a null but I don’t know is going well with nullability approach, because when calling the function need validate if it is not null. Just I want write the log if exists any problem


#4

You can do something like this:

return try {
    con.createQuery(sql).executeAndFetch(Task::class.java)
} catch (e: Exception) {
    logger.error("Error", e)
    throw e
}

In this case you will get a log message and the exception would be rethrown to the caller of the function.


#5

Perfect!

As reference for others beginners like me:

 fun getTasksBetweenDates() : List<Task> {
        val sql =
        "SELECT id, description, duedate " +
        "FROM task "
        val con = sql2o.open()

        return try {
            con.createQuery(sql).executeAndFetch(Task::class.java)
        } catch (e: Exception) {
            logger.error("Error", e)
            throw e
        } finally {
            con.close()
        }
    }

Thanks for your help!


#6

You can also try https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.io/use.html instead of local con variable if connection is Closable. This way you can skip finally part


#7

Hi Konstantin-Khvan

I tried something like this:

  fun getAllTasks(): List<Task> {
        val sql = "SELECT id, description, duedate " + "FROM tasks"

        sql2o.open().use { con -> return con.createQuery(sql).executeAndFetch(Task::class.java) }
    }

But show this errors:

Unresolved reference (in use)

Cannot infer a type for this parameter. Please specify it explicity. in con variable

and finally ‘return’ is not allowed here

I don’t understand how to implement use :sweat: and where I write the log error?

Could you write an example please?

Best Regards!


#8

Try moving ‘return’ from lambda to fun. Like so

return sql2o.open().use { con -> con.createQuery(sql).executeAndFetch(Task::class.java) }