Left Index

Kotlin Nested try..catch

When a try catch block is present inside another try catch block then it is called nested try catch block. If any exception occurs in the inner try catch block which is not handled in the inner catch blocks then the catch blocks of the outer try catch blocks are checked for that exception.

Syntax:
try {
	// code that can throw exception
	try {
		// code that can throw exception
	} catch (e: Exception) {
		// handle exception
	} finally {

	}
} catch (e: Exception) {
	// handle exception
} finally {

}

Example:
package com.theitbulls.kotlinex

import java.lang.ArithmeticException

fun main(args: Array<String>) {
	var array = intArrayOf(2, 4, 7, 1, 0)
	val num = 120
	try {
		for (index in array.indices) {
			try {
				println("Divide: ${num / array[index + 1]}")
			} catch (e: ArithmeticException) {
				println("ArithmeticException occur: ${e.toString()}")
			}
		}
	} catch (e: ArrayIndexOutOfBoundsException) {
		println("ArrayIndexOutOfBoundsException occur: ${e.toString()}")
	}
}
Output:
Divide: 30
Divide: 17
Divide: 120
ArithmeticException occur: java.lang.ArithmeticException: / by zero
ArrayIndexOutOfBoundsException occur: java.lang.ArrayIndexOutOfBoundsException: 5