Signup/Sign In

Kotlin Nested try catch

In this tutorial we will learn how to use nested try and catch block for exception handling in Kotlin. A try-catch block can be placed inside a try-catch block, this type of arrangement is known as nested try-catch block.

The syntax of nested try-catch block is:

try {
    // Try inside try
    try {
        
    }catch (exception: InnerException){
        // Handling inner exception
    }
}catch (exception: OuterException){
    // Handling outer exception
}

If any exception occurrs in the inner try block, then it is first checked with the inner catch block. If it is not handled there then it will be checked with outer catch block, and so on.

Kotlin Nested try-catch - Example:

Let us write a program using nested try-catch block:

fun main() {
    var a: Int = 0
    var b: Int = 0
    val result: Int
    try {
        try {
            a = Integer.parseInt(readLine())
            b = Integer.parseInt(readLine())
            println("Result of division is: ${a/b}")
        }catch (exception: NumberFormatException){
            println("Invalid inputs!!")
        }
    }catch (exception: ArithmeticException){
        println("Division by zero is not allowed!!")
    }
}

Here, inside the parent try block, a nested try block is added. We will try to take input from user and catch the exception if the format of the number is incorrect. Later we will perform division, and if any exception occurs during division, we will catch the exception with outer catch block,

The output for different inputs are:

  • a = 10, b = 5


    Result of division is: 2

  • a = 10, b = "Hello"


    Invalid inputs!!

  • a = 10, b = 0


    Division by zero is not allowed!!

Similarly, you can have as many nested try-catch block as you want. Although having too many try-catch blocks will make your code less readable.

Summary

In this tutorial we learned about nested try-catch block in Kotlin used for exception handling. We will discuss about the finally block in the next tutorial.



About the author:
I'm a writer at studytonight.com.