我正在尝试将此 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 中引发异常的唯一信息是 THIS .
除了去掉问号,因为没有必要,为什么不以同样的方式处理IOException
?处理这种情况的最佳方法是什么?
最佳答案
在 Kotlin 中,there's no checked exceptions ,不必声明任何异常,也不必强制捕获任何异常,当然,您可以。即使从 Java 类派生,您也不必声明方法抛出
的异常。
@Throws(SomeException::class)
仅用于 Java 互操作性,它允许在 Java 签名中编写带有 throws
的函数,以便在 Java 中可以(并且有必要)处理异常。
相反,公共(public) API 异常应记录在 KDoc with @throws
tag 中。 .
https://stackoverflow.com/questions/36528515/