Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin checked exceptions alternative

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?

like image 600
Jocky Doe Avatar asked Oct 13 '17 12:10

Jocky Doe


People also ask

Does Kotlin have checked exceptions?

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.

How do you catch error in Kotlin?

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.

How does Kotlin deal with try catch?

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.

How do I Rethrow Kotlin exception?

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.


1 Answers

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 ).

like image 127
GhostCat Avatar answered Oct 10 '22 19:10

GhostCat