In Kotlin,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.
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.
Evaluation Mechanics
The value yielded by thetry expression depends strictly on the execution path:
- Successful Execution: If no exception is thrown within the
tryblock, the expression evaluates to the value of the last expression inside thetryblock (1in the syntax above). - Caught Exception: If an exception is thrown and matches a
catchblock, the expression evaluates to the value of the last expression inside that specificcatchblock (2). - Uncaught Exception: If an exception is thrown but does not match any
catchblock, the exception propagates up the call stack. In this scenario, the execution results in abrupt completion. The static type of thetryexpression remains unchanged (determined at compile-time by thetryandcatchblocks), but no value is yielded at runtime.
Type Inference
The Kotlin compiler determines the static type of thetry expression by finding the least upper bound (the closest common supertype) of the types returned by the try block and all catch blocks.
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.
Master Kotlin with Deep Grasping Methodology!Learn More





