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 NumberFormatExceptionprintln("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.
Practice
(1/5)
1. What is the main purpose of using multiple catch blocks in Kotlin?
easy
A. To avoid using the try keyword
B. To run multiple try blocks at once
C. To handle different types of exceptions separately
D. To make the program run faster
Solution
Step 1: Understand exception handling
Multiple catch blocks allow handling different exceptions in different ways.
Step 2: Compare options
Only To handle different types of exceptions separately correctly describes handling different exception types separately.
Final Answer:
To handle different types of exceptions separately -> Option C