我开始学习Kotlin,但我无法理解如何处理异常。我知道那里没有经过检查的,但无论如何,如果我的方法抛出一个,我该怎么办?例如:
fun test(a: Int, b: Int) : Int {
return a / b
}
如果我除以零,我将得到ArithmeticException。那我该怎么办呢?
答案 0 :(得分:6)
您可以编写一个扩展函数,以在加载异常时返回默认值。
fun <T> tryOrDefault(defaultValue: T, f: () -> T): T {
return try {
f()
} catch (e: Exception) {
defaultValue
}
}
fun test(a: Int, b: Int) : Int = tryOrDefault(0) {
a / b
}
答案 1 :(得分:4)
ArithmeticException
是一个运行时异常,因此它也将在Java中取消选中。您处理它的选择也与Java相同:
try-catch
块包裹它。您可以从堆栈的任何位置捕获它,不需要任何throws
声明。由于Kotlin中没有经过检查的异常,因此也没有throws
关键字,但是如果您正在混合使用Kotlin和Java,并且您希望在Java代码中强制对已检查异常进行异常处理,您可以使用@Throws
注释来注释您的方法。
请参阅有关例外here的官方Kotlin文档。
答案 2 :(得分:4)
作为一个优点,因为kotlin中的try-catach可以返回值,您的代码可能如下所示:
fun test(a: Int, b: Int) : Int {
return try {a / b} catch(ex:Exception){ 0 /*Or any other default value*/ }
}
答案 3 :(得分:1)
您可以返回Try,以便客户端可以调用isSuccess或isFailure http://www.java-allandsundry.com/2017/12/kotlin-try-type-for-functional.html
您还可以返回Int吗?这样客户就会知道该值可能不存在(除以零时)。