Kotlin program of arithmetic exception handling using try-catch block

Kotlin example to demonstrate arithmetic exception handling using a try-catch block.
Submitted by IncludeHelp, on April 11, 2022

In this program, we will perform an arithmetic operation and handle arithmetic exceptions using a try-catch block.

Syntax for try-catch block:

try {
   // code that can throw exception
} catch(e: ExceptionName) {
   // catch the exception and handle it
}

Example:

// Importing the ArithmeticException class
import kotlin.ArithmeticException

fun main(args : Array<String>){
	var x = 10
	var y = 3
	try{
		println("10/3: " + x/y)

		x = 10
		y = 0 
		println("10/0: " + x/y)
	}
	catch(e: ArithmeticException){
		// caught and handles it
		println("Divide by zero exception")
	}
}

Output:

10/3: 3
Divide by zero exception

Kotlin Exception Handling Programs »




Comments and Discussions!

Load comments ↻





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