Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle exceptions in Kotlin?

Tags:

kotlin

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?

like image 462
VolodymyrH Avatar asked Nov 01 '17 16:11

VolodymyrH


People also ask

How does Kotlin handle multiple exceptions?

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.

How is exception handling done in Kotlin coroutines?

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.

What are the exceptions in Kotlin?

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.

How do you raise exception 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.


3 Answers

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.

like image 100
zsmb13 Avatar answered Oct 22 '22 08:10

zsmb13


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
}
like image 22
Jacky Choi Avatar answered Oct 22 '22 08:10

Jacky Choi


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

like image 22
CodesInTheDark Avatar answered Oct 22 '22 09:10

CodesInTheDark