Since Kotlin doesn't support checked exceptions then how to make a programmer aware that a method may throw exception
Simple example:
class Calculator (value: Int = 0) {
fun divide (dividend: BigDecimal, divider: BigDecimal) : BigDecimal {
return dividend / divider
}
}
Obviously the divide method may throw java.lang.ArithmeticException: Division by zero
exception and the creator of the library needs to warn the user of the class to put the invoke in a try-catch
clause
What's the mechanism for that awareness in Kotlin?
Kotlin does not have checked exceptions. There are many reasons for this, but we will provide a simple example that illustrates why it is the case. And that's not good. Just take a look at Effective Java, 3rd Edition, Item 77: Don't ignore exceptions.
In Kotlin, we use try-catch block for exception handling in the program. The try block encloses the code which is responsible for throwing an exception and the catch block is used for handling the exception. This block must be written within the main or other methods.
Kotlin try-catch block is used for exception handling in the code. The try block encloses the code which may throw an exception and the catch block is used to handle the exception. This block must be written within the method. Kotlin try block must be followed by either catch block or finally block or both.
In Kotin, we can use one try-catch-finally block to handle an exception. try block handles the code and if any exception occurs, it moves to the catch block and at last, finally block. Rethrowing an exception means rethrow an exception again in the catch block.
Given the fact that the language doesn't have a construct to make this explicit, the only thing left is: implicitly.
For example by putting javadoc that clearly tells the user of the method about what/why exceptions might be thrown at him. Or you use the @Throws annotation.
Maybe, maybe the kotlin team will add compiler warnings at some point to make up for this ( see here ).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With