Correct handled of try catch with nullabilty

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?

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

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

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.

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!

You can also try use - Kotlin Programming Language instead of local con variable if connection is Closable. This way you can skip finally part

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!

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

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