Reputation: 2019
I started to learn Kotlin and I can't understand how to handle exceptions. I know there's no checked ones, but anyway, what should I do if my method throws one? For example:
fun test(a: Int, b: Int) : Int {
return a / b
}
If I divide by zero, I will have ArithmeticException. So how should I handle such things?
Upvotes: 15
Views: 24004
Reputation: 191
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
You can also return Int? so that client will know that the value might not exist (when divided by zero).
Upvotes: 2
Reputation: 556
You may write an extension function to return a default value when encounting exception.
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
}
Upvotes: 18
Reputation: 2626
As a plus since try-catach in kotlin can return values your code could look like this:
fun test(a: Int, b: Int) : Int {
return try {a / b} catch(ex:Exception){ 0 /*Or any other default value*/ }
}
Upvotes: 6
Reputation: 89548
ArithmeticException
is a runtime exception, so it would be unchecked in Java as well. Your choices for handling it are the same as in Java too:
try-catch
block. You catch it anywhere up the stack from where it happens, you don't need any throws
declarations.Since there are no checked exceptions in Kotlin, there isn't a throws
keyword either, but if you're mixing Kotlin and Java, and you want to force exception handling of checked exceptions in your Java code, you can annotate your method with a @Throws
annotation.
See the official Kotlin docs about exceptions here.
Upvotes: 11