Kotlin doesn't have checked exceptions, i.e. ones where a function explicitly states what it could throw, and any callers are required to wrap the call in a try/catch
to deal with that possibility. Or not catch it, state that they themselves might produce that exception, and pass the responsibility to handle it up the chain.
That link explains the rationale, and links to some sources talking about the issue, but it's basically just how things are done (or not done) in Kotlin. There's a @Throws
annotation for interoperability with other languages where checked exceptions is how things are done, but it's not used in Kotlin itself.
If you want to inform the caller that an exception could be thrown, you're supposed to put it in the documentation comment for the function. There's a @throws
tag (or an @exception
one if you like) for that purpose, but like it says:
Documents an exception which can be thrown by a method. Since Kotlin does not have checked exceptions, there is also no expectation that all possible exceptions are documented, but you can still use this tag when it provides useful information for users of the class.
So it's purely informational really, and the user can choose to handle or not handle those potential exceptions - it's not required. And if you're writing your own functions, you might want to consider whether they should throw
an exception to the caller at all during normal, anticipated behaviour, or if they should return some kind of error value (like null) or an error type (e.g. a sealed class
that has some kind of failure subclass as well as success types).
// You could return this type instead of throwing an exception
sealed class Result<T> {
class Conversion<T>(data: T) : Result<T>()
class Error<T>(message: String) : Result<T>()
}
Basically, if you know a specific thing can go wrong during normal operation, is it really exceptional? Or just another kind of result to inform the caller about so it can take action if it needs to?