Industrial Training




Kotlin Finally Block


Kotlin finally block such block which is always executes whether exception is handled or not. So it is used to execute important code statement.


Kotlin finally Block Example 1


Let's see an example of exception handling in which exception does not occur.


fun main (args: Array< String>){  
    try {  
        val data = 10 / 5  
        println(data)  
    } catch (e: NullPointerException) {  
        println(e)  
    } finally {  
        println("finally block always executes")  
    }  
    println("below codes...")  
}  
fun main (args: Array< String>){  
    try {  
        val data = 10 / 5  
        println(data)  
    } catch (e: NullPointerException) {  
        println(e)  
    } finally {  
        println("finally block always executes")  
    }  
    println("below codes...")  
}  

Output:
2
finally block always executes
below codes...

Kotlin finally Block Example 2


Let's see an example of exception handling in which exception occurs but not handled.


fun main (args: Array< String>){  
    try {  
        val data = 5 / 0  
        println(data)  
    } catch (e: NullPointerException) {  
        println(e)  
    } finally {  
        println("finally block always executes")  
    }  
    println("below codes...")  
}  
fun main (args: Array< String>){  
    try {  
        val data = 5 / 0  
        println(data)  
    } catch (e: NullPointerException) {  
        println(e)  
    } finally {  
        println("finally block always executes")  
    }  
    println("below codes...")  
}  

Output:
finally block always executes
Exception in thread "main" java.lang.ArithmeticException: / by zero

Kotlin finally Block Example 3


Let's see an example of exception handling in which exception occurs and handled.


fun main (args: Array< String>){  
    try {  
        val data = 5 / 0  
        println(data)  
    } catch (e: ArithmeticException) {  
        println(e)  
    } finally {  
        println("finally block always executes")  
    }  
    println("below codes...")  
}  
fun main (args: Array< String>){  
    try {  
        val data = 5 / 0  
        println(data)  
    } catch (e: ArithmeticException) {  
        println(e)  
    } finally {  
        println("finally block always executes")  
    }  
    println("below codes...")  
}  

Output:
java.lang.ArithmeticException: / by zero
finally block always executes
below codes...


Hi I am Pluto.