Kotlin program of using try-catch as an expression

Kotlin example to demonstrate the use try-catch as an expression.
Submitted by IncludeHelp, on April 11, 2022

Kotlin try-catch block as an expression

As we know that an expression returns a value. In Kotlin, it's easy to use the try-catch block as an expression. And, the expression value will be either the last expression of the try block or the last expression of the catch block.

Consider the below example demonstrating the use of the try-catch block as an expression.

Example:

fun DivideOperation(x: Int, y: Int) : Any {
	return try {
		x/y
	}
	catch(exp:Exception){
		println(exp)
		"Divide by zero exception occured"
	}
}

// Main function
fun main(args: Array<String>) {
	// Call DivideOperation() functions
	// to use try-catch as an exception
	var res1 = DivideOperation(10, 3)
	println(res1)

	var res2 = DivideOperation(10, 0)
	println(res2)
}

Output:

3
java.lang.ArithmeticException: / by zero
Divide by zero exception occured

Kotlin Exception Handling Programs »





Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.