Signup/Sign In

Kotlin finally Block

In this tutorial, we will learn about finally block in Kotlin and what role does it play in exception handling in Kotlin. The finally block is used to carry out important cleanup operations, in case code execution has been disrupted by an exception.

The finally block can be placed after catch block or try block directly. Unlike catch block, there can be only one finally block.

Kotlin finally Keyword

The syntax of try-finally block is:

try {
  // Code to be executed  
}finally {
    // Body of finally block
}

And the syntax of try-catch-finally block is:

try {
    // Code to be executed
}catch (exception: SomeException) {
    // Body of Exception
}
finally { 
    // Body of finally block
}

The finally block will be executed in the following cases:

  1. Exception does not occur at all.

  2. Exception occurs and it is handled.

  3. Exception occurs and it is not handled.

Let us see example of each one of them.

Kotlin finally: Exception does not occur at all

In this case, the exception does not occur but finally block will be executed:

fun main() {
    try {
        val a: Int = 10
        val b: Int = 5
        println("Division of $a and $b results in: ${a/b}")
    }catch (exception: ArithmeticException) {
        println("Division by zero!!")
    }
    finally {
        println("Finally block is always executed.")
    }
}


Division of 10 and 5 results in: 2
Finally block is always executed.

Kotlin finally: Exception occurs and it is handled

In this case, the exception occurs and handled by catch block. At last, the finally block is executed:

fun main() {
    try {
        val a: Int = 10
        val b: Int = 0
        println("Division of $a and $b results in: ${a/b}")
    }catch (exception: ArithmeticException) {
        println("Division by zero!!")
    }
    finally {
        println("Finally block is always executed.")
    }
}


Division by zero!!
Finally block is always executed.

Kotlin finally:??????? Exception occurs and it is not handled

The exception occurs but it is not handled. The program will stop working but the finally block will be executed:

fun main() {
    try {
        val a: Int = 10
        val b: Int = 0
        println("Division of $a and $b results in: ${a/b}")
    } finally {
        println("Finally block is always executed.")
    }
}


Finally block is always executed.
Exception in thread "main" java.lang.ArithmeticException: / by zero
at FinallyKt.main(finally.kt:5)
at FinallyKt.main(finally.kt)

When to use Kotlin finally?

If you are wondering where I can use this finally block, then here are a few strong contenders for it:

  1. To close files opened during the code execution before the exception occured.

  2. To close DB connections, if created.

  3. To report the execution to the development team by sending an email or may be storing the exception in the database for later analysis.

  4. If you have a payment system, and an exception occurs during the execution, then finally blocks can be used to do the clean up of tokens, the state maintained, etc.

This is just the tip of the iceberg, when it comes to using the finally block.

Summary

In this tutorial we learned how and why to use the finally block in Kotlin during exception handling. In the next tutorial we will see how to deliberately throw an exception using the throw keyword.



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