Kotlin Try Catch – Return Value
Kotlin Try-Catch is an expression. Therefore we can return a value from try-catch. The return value should be the last statement in the try block, or it should be the last statement in the catch block.
If there is no exception, then the value in the try block would be returned. Else, if there is any exception, then the value in the corresponding catch block would be returned.
Examples
In the following program, we will try to convert an object x
to integer. We shall have this code in try block, and also return the parsed integer value. If there is an exception while conversion, we will return null in the catch block.
Main.kt
fun main(args: Array<String>) {
var x = "25"
val result: Int? = try { Integer.parseInt(x) } catch (e: NumberFormatException) { null }
print("Return value : $result")
}
Output
Return value : 25
Now, let us take a value for x
such that it throws Exception while conversion. The catch block should execute and null
value should be returned because null
is the last statement in the catch block.
Main.kt
fun main(args: Array<String>) {
var x = "25-ab"
val result: Int? = try { Integer.parseInt(x) } catch (e: NumberFormatException) { null }
print("Return value : $result")
}
Output
Return value : null
Conclusion
In this Kotlin Tutorial, we learned how to return a value from try-catch block, with the help of examples.