Left Index

Kotlin try..catch

Kotlin try-catch block is used for exception handling in the code. The try block encloses the code which may throw an exception and the catch block is used to handle the exception. This block must be written within the method. Kotlin try block must be followed by either catch block or finally block or both.

try {
	// code which can throw exception
} catch(e: Exception) {
	// handle exception here
} finally {
	// optional finally block  

Note: A try block can be associated with more than one catch blocks, however there can be only one finally block present.

Kotlin try catch block example
package com.theitbulls.kotlinex

fun main(args: Array<String>) {
	try {
		var divident = 10 / 0
		println("Divident: ${divident}")
	} catch (e: Exception) {
		println("Error: ${e.toString()}")
	} finally {
		println("This is finally block, that will run everytime")  
Error: java.lang.ArithmeticException: / by zero
This is finally block, that will run everytime