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.