在 Kotlin 方法中引发 Exception

我正在尝试将这段 Java 代码转换成 Kotlin:

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

问题是,当我实现这些方法时,我得到类似于

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

关于在 Kotlin 抛出异常,我找到的唯一信息是 这个

除了去掉问号,因为没有必要,为什么它不用同样的方式处理 IOException?处理这种情况的最佳方法是什么?

96602 次浏览

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.

In Java your functions are something like this

void foo() throws IOException{
throw new IOException();
}

But in Kotlin you can add annotation like below to force other Java classes to catch it. However, as other answers have pointed out, it doesn't have any meaning among Kotlin classes.

@Throws(IOException::class)
fun foo() {
throw IOException()
}

Source kotlinlang.org