Using the try block as an expression

When we run program code, we deal with expressions and statements all the time. It's very important to understand the difference between these. Let's look at the following code:

1 + 1

This code is an expression because it contains variables, operators, and returns a single result. If a standalone element of program code represents an action, it is a statement:

println("Hello")

In the context of this section, the main point for us is that an expression returns something. In Kotlin, the try { ... } catch { ... } finally { ... } block is an expression and we can write something like this:

fun loadValue(): Int = throw Exception()

fun main(args: Array<String>) {
println(try { loadValue() } catch (exception: Exception) { 4 })
}

Under the hood, this code works in the same way as if we were to write it in Java. To check this, you can decompile this code to Java:

public final class Example6Kt {
public static final int loadValue() {
throw (Throwable)(new Exception());
}

public static final void main(@NotNull String[] args) {
Intrinsics.checkParameterIsNotNull(args, "args");

int var1;
try {
var1 = loadValue();
} catch (Exception var3) {
var1 = 4;
}

System.out.println(var1);
}
}

As you can see, there is no magic here. In contrast with Java, all control flow elements in Kotlin are expressions, which provides a more concise solution for common issues.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.216.77.153