throws Exception in a method with Kotlin

cesards picture cesards · Apr 10, 2016 · Viewed 54k times · Source

I'm trying to convert this Java code to Kotlin:

public class HeaderInterceptor implements Interceptor {
  @Override public Response intercept(Chain chain) throws IOException {
    return null;
  }
}

The problem is, when I implement the methods, I get something like

class JsonHeadersInterceptor : Interceptor {
    override fun intercept(chain: Interceptor.Chain?): Response? {
        throw UnsupportedOperationException()
    }
}

The only info I've found talking about throwing exceptions in Kotlin is THIS.

Apart from removing the question mark, because it's not necessary, why it doesn't handle the IOException the same way? What is the best approach to handle this situation?

Answer

hotkey picture hotkey · Apr 10, 2016

In Kotlin, there's no checked exceptions, no exceptions have to be declared and you aren't forced to catch any exception, though, of course, you can. Even when deriving from a Java class, you don't have to declare exceptions that a method throws.

@Throws(SomeException::class) is just intended for Java interoperability, which allows one to write a function with throws in Java signature, so that in Java it will be possible (and necessary) to handle the exception.

Instead, public API exceptions should be documented in KDoc with @throws tag.