ADVERTISEMENT
ADVERTISEMENT

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 »


ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!



ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.