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 try
–catch
is also similar to that used in Java. In Kotlin, here's how a try
–catch
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, try
–catch
is special as it enables it to be used as an expression. In this article, we will see how we can use try
–catch
as an expression.
Getting ready
You need to install a preferred development environment that compiles and runs Kotlin. You can also use the command line for this purpose, for which you need Kotlin compiler installed, along with JDK. I am using IntelliJ IDE to compile and run my Kotlin code...