Kotlin Multiple Catch Block Tutorial With Example

In this tutorial, we will learn about kotlin multiple catch block with try block. We will see why do we need to use multiple catch block? how do we use it? etc.

Syntax of kotlin multiple catch block

try {
    // Code that may generate error
} catch(e: ExceptionName1) {
    // exception name 1 block
} catch(e: ExceptionName2) {
    // exception name 2 block
}

Why do we use multiple catch block in kotlin

To understand the answer clearly, let’s take an example –

Can you guess the output of below program?

fun main(args: Array<String>) {
    val numb = getInt("100.9")
    println(numb)
}

fun getInt(s: String): Int {
    return try {
        Integer.parseInt(s)
    } catch (e: ArithmeticException) {
        0
    }
}

When you run the program, you will get an exception –

Exception in thread "main" java.lang.NumberFormatException: For input string: "100.9"
	at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)

You may be thinking why did it happen? Output should have been 0 because we have provided a wrong input 100.9. So, exception will occur and it will be caught by catch block. Hence the result will be 0.

But, look closely into the type of exception we are handling into catch block. It’s ArithmeticException. It has nothing to do with wrong input value that results into wrong number format. Arithmetic exception occurs when there is a calculation error like divide by zero.

So, before using any Exception class, you check if it is really appropriate in that case or not.

So, above program can be written as –

fun main(args: Array<String>) {
    val numb = getInt("100.9")
    println(numb)
}

fun getInt(s: String): Int {
    return try {
        Integer.parseInt(s)
    } catch (e: NumberFormatException) {
        0
    }
}

Now, when you run above program, output will be
0

If you think, there are possibilities of multiple exceptions, you should use multiple catch block.
That’s only scenario when we should use kotlin multiple catch block.

fun main(args: Array<String>) {
    val result = computeDivision("100", 0)
    println(result)
}

fun computeDivision(a: String, b: Int): Int {
    return try {
        Integer.parseInt(a) / b
    } catch (e: NumberFormatException) {
        println("NumberFormatException occurred: ")
        0
    } catch (e: ArithmeticException) {
        println("ArithmeticException occurred: ")
        -1
    }
}

When you run the program, you will get below output –
ArithmeticException occurred:
-1

When you would have called computeDivision function as computeDivision(“100s”, 0), the program result would have been –
NumberFormatException occurred:
0

That’s why and how we use multiple catch block with try block in kotlin.

Did you know?
Only one exception will be handled at a time even when you have written multiple catch blocks in the program. So, you should be careful while using an exception class.

Some important points on kotlin multiple catch block

1. All the catch block should be placed from specific to general order of exception. For example, NumberFormatException must be used before Exception. Example,

 fun main(args: Array<String>) {
    val result = computeDivision("100s", 0)
    println(result)
}

fun computeDivision(a: String, b: Int): Int {
    return try {
        Integer.parseInt(a) / b
    } catch (e: Exception) {
        println("Exception occurred")
        -999
    } catch (e: NumberFormatException) {
        println("NumberFormatException occurred: ")
        0
    } catch (e: ArithmeticException) {
        println("ArithmeticException occurred: ")
        -1
    }
}

When you run the program, output will be –
Exception occurred
-999

The output will be same even when you call computeDivision() function as computeDivision(“100”, 0). This is because you have handled master exception class before all other exception. Exception class is used to handle all exceptions in kotlin.

2. We should use Exception only when we are not sure about the type of exception that may be thrown in the program. Also, Exception class should be used in last catch block.

So, above program can be written as –

fun main(args: Array<String>) {
    val result = computeDivision("100s", 0)
    println(result)
}

fun computeDivision(a: String, b: Int): Int {
    return try {
        Integer.parseInt(a) / b
    } catch (e: NumberFormatException) {
        println("NumberFormatException occurred: ")
        0
    } catch (e: ArithmeticException) {
        println("ArithmeticException occurred: ")
        -1
    } catch (e: Exception) {
        println("Exception occurred")
        -999
    }
}

When you run above program, you will get output –
NumberFormatException occurred:
0

Exercises on Kotlin Multiple catch block

1. Guess the output of below program

fun main(args: Array<String>) {
    val result = computeDivision("100", 0)
    println(result)
}

fun computeDivision(a: String, b: Int): Int {
    return try {
        Integer.parseInt(a) / b
    } catch (e: NumberFormatException) {
        println("NumberFormatException occurred: ")
        0
    } catch (e: ArithmeticException) {
        println("ArithmeticException occurred: ")
        -1
    } catch (e: Exception) {
        println("Exception occurred")
        -999
    }
}

2. Guess the output of below program

fun main(args: Array<String>) {
    val arr = intArrayOf(1, 2, 3.5, 4, 5, 6)
    try {
        print(arr[6])
    } catch (e: ArrayIndexOutOfBoundsException) {
        print("Exception occurred: ArrayIndexOutOfBoundsException")
    }
}

3. Guess the output of below program

fun main(args: Array<String>) {
    val arr = intArrayOf(1, 2, 3, 4, 5, 6)
    try {
        print(arr[6])
    } catch (e: ArrayIndexOutOfBoundsException) {
        print("Exception occurred: ArrayIndexOutOfBoundsException")
    } catch(e: Exception) {
        print("Exception occurred: Exception")
    }
}

That’s end of tutorial on Kotlin Multiple catch block.

Leave a Reply