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.

In Kotlin, try is an expression rather than a statement, meaning it evaluates to a value that can be assigned to a variable, passed as an argument, or returned from a function. The evaluated result of the expression is determined by the last expression of the executed block.
val result = try {
    // Execution block
    1
} catch (e: IllegalArgumentException) {
    // Exception handling block
    2
} finally {
    // Cleanup block
    3
}

Evaluation Mechanics

The value yielded by the try expression depends strictly on the execution path:
  1. Successful Execution: If no exception is thrown within the try block, the expression evaluates to the value of the last expression inside the try block (1 in the syntax above).
  2. Caught Exception: If an exception is thrown and matches a catch block, the expression evaluates to the value of the last expression inside that specific catch block (2).
  3. Uncaught Exception: If an exception is thrown but does not match any catch block, the exception propagates up the call stack. In this scenario, the execution results in abrupt completion. The static type of the try expression remains unchanged (determined at compile-time by the try and catch blocks), but no value is yielded at runtime.

Type Inference

The Kotlin compiler determines the static type of the try expression by finding the least upper bound (the closest common supertype) of the types returned by the try block and all catch blocks.
val result = try {
    "Success" // Type: String
} catch (e: Exception) {
    42        // Type: Int
}
// The inferred type of 'result' is 'Any', as it is the common supertype of String and Int.
To maintain strict typing, the last expressions in both the try and catch blocks should ideally evaluate to the same type or a shared specific interface/superclass.

The finally Block

The finally block is optional and executes after the try and catch blocks complete, regardless of whether an exception was thrown. Crucially, the finally block does not affect the evaluated result of the try expression. Even if the finally block contains a returnable value or expression, it is ignored by the assignment.
val result: Int = try {
    10
} catch (e: Exception) {
    20
} finally {
    30 // This value is executed but discarded. It does not become the value of 'result'.
}
// 'result' will be 10.
Master Kotlin with Deep Grasping Methodology!Learn More