简体   繁体   English

Kotlin检查了例外情况

[英]Kotlin checked exceptions alternative

Since Kotlin doesn't support checked exceptions then how to make a programmer aware that a method may throw exception 由于Kotlin不支持检查异常,因此如何让程序员意识到方法可能会抛出异常

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 显然,divide方法可能会抛出java.lang.ArithmeticException: Division by zero异常,并且库的创建者需要警告类的用户将调用放在try-catch子句中

What's the mechanism for that awareness in Kotlin? 在Kotlin,这种意识的机制是什么?

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. 例如,通过将javadoc清楚地告诉用户该方法可能会向他抛出异常的原因。 Or you use the @Throws annotation. 或者您使用@Throws注释。

Maybe, maybe the kotlin team will add compiler warnings at some point to make up for this ( see here ). 也许,也许kotlin团队会在某些时候添加编译器警告来弥补这一点(见这里 )。

You can return Try so that client can call isSuccess or isFailure http://www.java-allandsundry.com/2017/12/kotlin-try-type-for-functional.html 您可以返回Try,以便客户端可以调用isSuccess或isFailure http://www.java-allandsundry.com/2017/12/kotlin-try-type-for-functional.html

You can also return nullable type BigDecimal? 你还可以返回可空类型BigDecimal? so that client will know that the value might not exist (when divided by zero you can return null). 这样客户端就会知道该值可能不存在(当除以零时,您可以返回null)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM