Kotlin Programming Cookbook
上QQ阅读APP看书,第一时间看更新

Using try–catch as an expression

Exceptions in Kotlin are both similar and different compared to those in Java. In Kotlin, Throwable is the superclass of all the exceptions, and every exception has a stack trace, message, and an optional cause.

The structure of trycatch is also similar to that used in Java. In Kotlin, here's how a trycatch statement looks:

try {
// some code to execute
}
catch (e: SomeException) {
// exception handler
}
finally {
// optional finally block
}

At least one catch block is mandatory and the finally block is optional, and so it can be omitted.

In Kotlin, trycatch is special as it enables it to be used as an expression. In this article, we will see how we can use trycatch as an expression.