Q:

Kotlin program of using try-catch as an expression

0

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.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now