Industrial Training




Multiple Catch Block


We can use multiple catch block in our code. Kotlin multiple catch blocks are used when we are using different types of operation in try block which may causes different exceptions in try block.


Kotlin multiple catch block example 1


Let's see an example of multiple catch blocks. In this example we will are performing different types of operation. These different types of operation may generate different types of exceptions.


 fun main(args: Array< String>){  
    try {  
        val a = IntArray(5)  
        a[5] = 10 / 0  
    } catch (e: ArithmeticException) {  
        println("arithmetic exception catch")  
    } catch (e: ArrayIndexOutOfBoundsException) {  
        println("array index outofbounds exception")  
    } catch (e: Exception) {  
        println("parent exception class")  
    }  
    println("code after try catch...")  
}  
 fun main(args: Array< String>){  
    try {  
        val a = IntArray(5)  
        a[5] = 10 / 0  
    } catch (e: ArithmeticException) {  
        println("arithmetic exception catch")  
    } catch (e: ArrayIndexOutOfBoundsException) {  
        println("array index outofbounds exception")  
    } catch (e: Exception) {  
        println("parent exception class")  
    }  
    println("code after try catch...")  
} 

Output:
arithmetic exception catch
code after try catch...

Rule: All catch blocks must be placed from most specific to general i.e. catch for ArithmeticException must come before catch for Exception.


What happen when we catch from general exception to specific exception?


It will generate warning. For example:
Let's modify above code and place catch block from general exception to specific exception.


fun main(args: Array< String>){  
    try {  
        val a = IntArray(5)  
        a[5] = 10 / 0  
    }  
    catch (e: Exception) {  
        println("parent exception catch")  
    }  
    catch (e: ArithmeticException) {  
        println("arithmetic exception catch")  
    } catch (e: ArrayIndexOutOfBoundsException) {  
        println("array index outofbounds exception")  
    }  
      
    println("code after try catch...")  
}  
fun main(args: Array< String>){  
    try {  
        val a = IntArray(5)  
        a[5] = 10 / 0  
    }  
    catch (e: Exception) {  
        println("parent exception catch")  
    }  
    catch (e: ArithmeticException) {  
        println("arithmetic exception catch")  
    } catch (e: ArrayIndexOutOfBoundsException) {  
        println("array index outofbounds exception")  
    }  
      
    println("code after try catch...")  
}   			  

Output at compile time
warning : division by zero
a[5] = 10/0

Output at run time
parent exception catch
code after try catch...



Hi I am Pluto.