Left Index

Kotlin Multiple try..catch

A try block can have multiple catch blocks. When we are not sure what all exceptions can occur inside the try block then it is always a good idea to have multiple catch blocks for the potential exceptions and in the last catch block have the parent exception class to handle the remaining exceptions that are not specified by catch blocks.

Example:
package com.theitbulls.kotlinex

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

Another Example:
package com.theitbulls.kotlinex

fun main(args: Array<String>) {
	try {
		var array = IntArray(5)
		array[10] = 10 / 2
		println("Divident: ${array[5]}")
	} catch(e: ArrayIndexOutOfBoundsException) {
		println("Error: ${e.toString()}")
	} catch (e: ArithmeticException) {
		println("Error: ${e.toString()}")
	} finally {
		println("This is finally block, that will run everytime")  
	}
}
Output:
Error: java.lang.ArrayIndexOutOfBoundsException: 10
This is finally block, that will run everytime