Errors in Kotlin
In Kotlin, it’s idiomatic to communicate errors via exceptions, which is different from the approach used in some other languages. Kotlin provides a rich set of built-in exception types, and you can also create custom exceptions.
In this Kotlin code:
We define a function
f
that can throw an exception. The@Throws
annotation is used to indicate that this function may throw an exception.Instead of returning errors, we throw exceptions when an error condition is met.
We define custom exceptions
OutOfTeaException
andPowerException
by extending theException
class.The
makeTea
function demonstrates how to throw these custom exceptions.In the
main
function, we usetry-catch
blocks to handle potential exceptions. This is similar to error checking in other languages.We use Kotlin’s
when
expression (similar to switch in other languages) to check the type of the caught exception and respond accordingly.Kotlin’s smart casting allows us to use
is
checks in thewhen
expression, which automatically casts the exception to the correct type in each branch.
This approach leverages Kotlin’s exception handling mechanism, which is more idiomatic for the language than returning error values. It allows for clear separation of normal and error paths in the code, while still providing detailed information about what went wrong when an error occurs.
When you run this program, you should see output similar to:
This demonstrates how Kotlin handles both successful operations and various error conditions using its exception mechanism.