Try expression in Kotlin
The Try can be also used as Try expression in Kotlin. The Try expression returns the last expression of try block or last expression of catch. The finally block working doesn’t get affected in Try expression. To understand Try expression is Kotlin please check out the following example program.
Example Program without Exception:
fun main(args: Array<String>){
val str = div(10,2)
println("Ans "+str)
}
fun div(num1: Int, num2: Int): Int{
return try {
num1/num2
} catch (e: ArithmeticException) {
0
}
}
Output:
Ans 5
Example Program with Exception:
fun main(args: Array<String>){
val str = div(10,0)
println("Ans "+str)
}
fun div(num1: Int, num2: Int): Int{
return try {
num1/num2
} catch (e: ArithmeticException) {
0
}
}
Output:
Ans 0
Spread the love:
Please share this page on social media with your friends..
![]() |
![]() |
![]() |
Message Help us to make this site best. In case you find any mistake in this tutorial please inform us.