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?
Kotlin does not support throwing multiple exceptions at the same time, however we can implement this functionality using some other functions provided by the Kotlin library.
A generic way to handle exception in kotlin is to use a try-catch block. Where we write our code which might throw an exception in the try block, and if there is any exception generated, then the exception is caught in the catch block.
The exceptions in Kotlin is pretty similar to the exceptions in Java. All the exceptions are descendants of the “Throwable” class. Following example shows how to use exception handling technique in Kotlin.
If you want to alert callers about possible exceptions when calling Kotlin code from Java, Swift, or Objective-C, you can use the @Throws annotation.
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.
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
}
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).
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