0
0
Kotlinprogramming~5 mins

Multiple catch blocks in Kotlin

Choose your learning style9 modes available
Introduction

Multiple catch blocks let you handle different errors in different ways. This helps your program respond correctly to each problem.

When you want to handle different types of errors separately.
When you want to give specific messages for different problems.
When you want to recover differently depending on the error.
When you want to log errors differently based on their type.
Syntax
Kotlin
try {
    // code that might throw exceptions
} catch (e: ExceptionType1) {
    // handle ExceptionType1
} catch (e: ExceptionType2) {
    // handle ExceptionType2
} catch (e: Exception) {
    // handle any other exceptions
}

Each catch block handles a specific type of exception.

The last catch block can catch all other exceptions as a fallback.

Examples
This example catches a number format error first, then any other error.
Kotlin
try {
    val number = "abc".toInt()
} catch (e: NumberFormatException) {
    println("Not a valid number")
} catch (e: Exception) {
    println("Some other error")
}
This example catches an index error separately from other errors.
Kotlin
try {
    val list = listOf(1, 2, 3)
    println(list[5])
} catch (e: IndexOutOfBoundsException) {
    println("Index is out of range")
} catch (e: Exception) {
    println("Unknown error")
}
Sample Program

This program tries to convert a string to a number. It catches the specific number format error and prints a message. If any other error happens, it catches that too.

Kotlin
fun main() {
    try {
        val input = "abc"
        val number = input.toInt()  // This will cause NumberFormatException
        println("Number is $number")
    } catch (e: NumberFormatException) {
        println("Caught NumberFormatException: Input is not a number")
    } catch (e: Exception) {
        println("Caught some other exception")
    }
}
OutputSuccess
Important Notes

Order matters: put more specific exceptions before general ones.

Use multiple catch blocks to keep error handling clear and organized.

Summary

Multiple catch blocks let you handle different errors separately.

Put specific exceptions first, then general ones last.

This helps your program respond better to problems.