Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

The try-finally construct in Kotlin is a control flow mechanism that guarantees the execution of a specific block of code (the finally block) immediately after a try block completes, regardless of whether the try block terminates normally, throws an exception, or encounters a control flow jump such as return, break, or continue. In Kotlin, a try block must be followed by either a catch block, a finally block, or both. The try-finally combination (without catch) is syntactically valid and is used when exception handling is delegated to a higher level in the call stack, but local cleanup or state reset is strictly required.
try {
    // Protected execution block
} finally {
    // Guaranteed execution block
}

Execution Mechanics

  1. Normal Termination: The try block executes to completion. Immediately afterward, the finally block executes. Control flow then proceeds to the next statement following the try-finally construct.
  2. Exception Propagation: If an exception is thrown within the try block, execution of the try block halts immediately. The finally block is executed. Once the finally block completes, the original exception continues to propagate up the call stack.
  3. Control Flow Interruption: If a return statement is evaluated inside the try block, the finally block is executed before the control is actually returned to the caller.

Expression Semantics

Unlike Java, try in Kotlin is an expression, meaning it can evaluate to a value and be assigned to a variable. However, the finally block does not affect the evaluated result of the try expression. The value of the try expression is determined solely by the last expression evaluated in the try block (or the catch block, if present). The finally block is executed strictly for its side effects.
val result: Int = try {
    // The last expression here becomes the value of 'result'
    42 
} finally {
    // This block executes, but its evaluation does not alter 'result'
    100 // This value is discarded
}
// result == 42

Return Overriding (Edge Case)

If a return statement is explicitly placed inside the finally block, it overrides any pending control flow from the try block. This includes overriding a return statement executed within the try block, or swallowing an unhandled exception thrown within the try block.
fun evaluate(): String {
    try {
        throw RuntimeException("Exception in try")
    } finally {
        // This return suppresses the RuntimeException and forces the function to return "Overridden"
        return "Overridden" 
    }
}
Note: Placing a return, break, or continue inside a finally block is generally flagged by static analysis tools due to this destructive overriding behavior.
Master Kotlin with Deep Grasping Methodology!Learn More