I am a newbie to Kotlin programming. While going through the advantages of Kotlin over Java I came across this claim that by avoiding checked exceptions Kotlin achieves type safety. Also I do not understand how the exception handled with an empty catch block harms type-safety(I read it on a blog)? Can it be explained with an example?
By itself, removing checked exceptions doesn't increase type safety. Kotlin's claim of improved type safety comes from the other features and idioms it introduces to replace checked exceptions.
In Kotlin, exceptions are not intended to be used for recoverable failures. They're only there to handle bugs and logic errors.
As a rule of thumb, you should not be catching exceptions in general Kotlin code. [...] Use exceptions for logic errors, type-safe results for everything else. Don’t use exceptions as a work-around to sneak a result value out of a function.
https://elizarov.medium.com/kotlin-and-exceptions-8062f589d07
The "type-safe results" referred to above are things like sealed classes, which provide a very controlled way to enumerate the possible types that a function can return. For example, you could have a sealed class with one implementation for a successful result and other implementations for each of the possible types of failure.
If there’s a single error condition and you are only interested in success or failure of the operation without any details, then prefer using
null
to indicate a failure. If there are multiple error conditions, then create a sealed class hierarchy to represent various results of your function. Kotlin has all those needs covered by design, including a powerfulwhen
expression.https://elizarov.medium.com/kotlin-and-exceptions-8062f589d07