How to handle exceptions in Kotlin?

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*/ }
}

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


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:

  • Ignore it and get a crash at runtime
  • Wrap it with a 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
}

Tags:

Kotlin