Kotlin Try Catch Return Result

July 25, 2018

try is an expression, i.e. it may have a return value:

val result: Int? = try { parseInt(input) } catch (e: NumberFormatException) { null }
val user = try {
    signinUser(googleUserId)
}
catch (e: Exception) {
    e.printStackTrace()
    null
}

You can also do

val finalName = name ?: throw IllegalArgumentException("Name required")

References:

This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.