Open In App

Kotlin Nested try block and multiple catch block

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

Nested try block –

In this article, we are going to learn nested try-catch block and multiple catch block. Nested try block is a block in which we can implement one try catch block into another try catch block.

The requirement of nested try-catch block arises when an exception occurs in the inner try-catch block is not handled by the inner catch blocks then the outer try-catch blocks are checked for that exception.

Syntax of nested try block –

// outer try block
try    
{    
    // inner try block   
    try    
    {    
        // code that can throw exception   
    }    
    catch(e: SomeException)    
    {    
     // catch the exception and handle it
    }    
}    
catch(e: SomeException)    
{    
// catch the exception and handle it
}    

Kotlin program of nested try block –

Kotlin




fun main(args: Array<String>) {
    val numbers = arrayOf(1,2,3,4)
  
    try {
        for (i in numbers.indices) {
            try {
                var n = (0..4).random()
                println(numbers[i+1]/n)
  
            } catch (e: ArithmeticException) {
                println(e)
            }
        }
    } catch (e: ArrayIndexOutOfBoundsException) {
        println(e)
    }
}


Output:

2
3
java.lang.ArithmeticException: / by zero
java.lang.ArrayIndexOutOfBoundsException: Index 4 out of bounds for length 4

Note: This output is generated for some random number. If you will get some different output then don’t worry because your output will be according to the random number generated at that instant of time.

Multiple catch block –

A try block can have more than one catch blocks. When we are not sure what type of exception can occur inside the try block then we can put multiple catch blocks for the potential exceptions and in the last catch block we can put the parent exception class to handle all the remaining exceptions which are not specified by catch blocks in the program.

Syntax for multiple catch –

try {
    // code may throw exception
} catch(e: ExceptionNameOne) {
    // catch the exception one and handle it
} catch(e: ExceptionNameTwo) {
    // catch the exception two and handle it
}

Kotlin program of multiple catch blocks –

Kotlin




import java.util.Scanner
  
object Test {
    @JvmStatic
    fun main(args: Array<String>) {
        val sc = Scanner(System.`in`)
        try {
            val n = Integer.parseInt(sc.nextLine())
            if (512 % n == 0)
                println("$n is a factor of 512")
        } catch (e: ArithmeticException) {
            println(e)
        } catch (e: NumberFormatException) {
            println(e)
        }
    }
}


Input 1:

GeeksforGeeks

Output 1:

java.lang.NumberFormatException: For input string: "GeeksforGeeks"

Input 2:

0

Output 2:

java.lang.ArithmeticException: / by zero

In the above program for input 1, we use a string but require an integer value to get the factors of the numbers. So, it throw the NumberFormatException.
For input 2, we input zero but we can’t divide an integer by zero. So, it throws ArithmeticException.

Use of when in catch block –

In Kotlin, we can use when expression to replace multiple catch blocks. In the below, we will show how to use when expression.

Kotlin




import java.lang.NumberFormatException
import java.util.Scanner
  
object Test {
    @JvmStatic
    fun main(args: Array<String>) {
        val sc = Scanner(System.`in`)
        try {
            val n = Integer.parseInt(sc.nextLine())
            if (512 % n == 0)
                println("$n is a factor of 512")
        } catch (e: Exception ) {
          when(e){
              is ArithmeticException -> { println("Arithmetic Exception: Divide by zero") }
              is NumberFormatException -> { println("Number Format Exception ") }
          }
        }
    }
}


Input 1:

GeeksforGeeks

Output 1:

Number Format Exception 

Input 2:

0

Output 2:

Arithmetic Exception: Divide by zero


Last Updated : 28 Mar, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads