15

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?

3
  • try-catch works pretty much the same way as it does in Java. You can see it in the docs about exceptions here. Commented Nov 1, 2017 at 16:32
  • @zsmb13 So it's like I can handle "checked" exceptions, just don't write throws in method signature? And it's ok to write like that? If so, pls write it as answer and I will close this question. Commented Nov 1, 2017 at 16:35
  • 1
    return Try<Int> so that client can call isSuccess or isFailure java-allandsundry.com/2017/12/… Commented Jul 5, 2018 at 19:59

4 Answers 4

18

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
}
Sign up to request clarification or add additional context in comments.

Comments

11

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.

Comments

6

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

Comments

2

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.