The finally block lets you run code that must happen no matter what, like cleaning up or closing files.
0
0
Finally block behavior in Kotlin
Introduction
You open a file and want to make sure it closes even if an error happens.
You start a network connection and want to close it no matter what.
You allocate resources and want to release them safely after use.
You want to print a message after trying some code, whether it worked or failed.
Syntax
Kotlin
try { // code that might throw an exception } catch (e: Exception) { // code to handle the exception } finally { // code that always runs }
The finally block runs after try and catch, no matter what.
If there is a return statement in try or catch, finally still runs before returning.
Examples
This runs the
try code and then always runs the finally block.Kotlin
try { println("Trying something") } finally { println("Always runs") }
Even if an error happens and is caught, the
finally block runs.Kotlin
try { throw Exception("Oops") } catch (e: Exception) { println("Caught: ${e.message}") } finally { println("Cleanup") }
The
finally block runs before the function returns a value.Kotlin
fun test(): String { try { return "From try" } finally { println("Finally runs before return") } } println(test())
Sample Program
This program tries to divide by zero, which causes an error. The catch block handles it, and the finally block runs no matter what. Then the program continues.
Kotlin
fun main() { try { println("Start try") val result = 10 / 0 // This causes an exception println("Result: $result") } catch (e: ArithmeticException) { println("Caught exception: ${e.message}") } finally { println("This always runs") } println("Program continues") }
OutputSuccess
Important Notes
Use finally to keep your program safe by cleaning up resources.
If finally has a return statement, it can override returns from try or catch. Avoid this to prevent confusion.
Summary
The finally block always runs after try and catch.
It is useful for cleanup tasks like closing files or releasing resources.
Even if an exception happens or a return occurs, finally runs before the method exits.