![]() |
VOOZH | about |
In Kotlin, exception handling allows developers to manage errors gracefully and prevent application crashes. In this article, we will explore two advanced exception handling concepts in Kotlin:
A nested try block is when you place one try-catch block inside another. This is useful when different parts of your code may throw different types of exceptions, and you want to handle them at different levels. If an exception occurs inside the inner try block and is not handled by its corresponding catch, the outer catch block is checked next. This allows for layered or fallback error handling.
Syntax -
try {
// Outer try block
try {
// Inner try block
// Code that may throw exception
} catch (e: SomeException) {
// Handle specific exception for inner block
}
} catch (e: SomeException) {
// Handle exception not caught by inner block
}
Example:
Output:
3
java.lang.ArrayIndexOutOfBoundsException: Index 4 out of bounds for length 4
java.lang.ArithmeticException: / by zero
Note: Since the value of b is hardcoded to 0, and the array has only 4 elements (index 0–3), exceptions will always occur in this example. You can experiment with different values for different results.
In Kotlin, a single try block can be followed by multiple catch blocks. This is helpful when the code inside the try block can throw different types of exceptions, and you want to handle each type separately.
Syntax -
try {
// Code that may throw different types of exceptions
} catch (e: ExceptionType1) {
// Handle ExceptionType1
} catch (e: ExceptionType2) {
// Handle ExceptionType2
}
Example:
Input 1:
GeeksforGeeksOutput 1:
Number Format Exception: Please enter a valid integer.Input 2:
0Output 2:
Arithmetic Exception: Cannot divide by zero.If the user inputs a non-integer string like "GeeksforGeeks", toInt() throws a NumberFormatException. If the user inputs 0, division by zero causes an ArithmeticException.
Kotlin allows you to simplify multiple catch blocks by using a when expression inside a single catch block. This approach improves code readability, especially when you want to perform different actions based on the type of exception.
Example:
Input 1:
GeeksforGeeksOutput 1:
Number Format ExceptionInput 2:
0Output 2:
Arithmetic Exception: Divide by zero