The try, catch, and finally Blocks
Learn how to effectively use try-catch expressions and finally blocks in Kotlin for advanced error handling and resource cleanup.
We'll cover the following...
Using try
-catch
as an expression
The try
-catch
structure can be used as an expression. It returns the result of a try
block if no exception occurs. If an exception occurs and is caught, then the try
-catch
expression returns the result of the catch
block.
Press + to interact
fun main() {val a = try {1} catch (e: Error) {2}println(a) // 1val b = try {throw Error()1} catch (e: Error) {2}println(b) // 2}
...