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.
Page Contents
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
Parvesh Sandila is a results-driven tech professional with 8+ years of experience in web and mobile development, leadership, and emerging technologies.
After completing his Master’s in Computer Applications (MCA), he began his journey as a programming mentor, guiding 100+ students and helping them build strong foundations in coding. In 2019, he founded Owlbuddy.com, a platform dedicated to providing free, high-quality programming tutorials for aspiring developers.
He then transitioned into a full-time programmer, where his hands-on expertise and problem-solving skills led him to grow into a Team Lead and Technical Project Manager, successfully delivering scalable web and mobile solutions. Today, he works with advanced technologies such as AI systems, RAG architectures, and modern digital solutions, while also collaborating through a strategic partnership with Technobae (UK) to build next-generation products.
