[英]throws Exception in a method with Kotlin
我正在尝试将此 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 中, 没有受检异常,不需要声明异常,并且您不会被迫捕获任何异常,当然,您可以。 即使从 Java 类派生,您也不必声明方法throws
。
@Throws(SomeException::class)
仅用于 Java 互操作性,它允许编写带有 Java 签名的throws
的函数,以便在 Java 中可以(并且必须)处理异常。
相反,公共 API 异常应该用@throws
标签记录在KDoc 中。
在Java 中你的函数是这样的
void foo() throws IOException{
throw new IOException();
}
但是在Kotlin 中,您可以添加如下所示的注释来强制其他 Java 类捕获它。 但是,正如其他答案所指出的那样,它在 Kotlin 类中没有任何意义。
@Throws(IOException::class)
fun foo() {
throw IOException()
}
Kotlin中的所有异常类都是Throwable类的后代
@Throws(IOException :: class)在方法之前使用此行
还可以像这样使用throw Exception(“ Hi There!”)
查看此以获得详细说明https://kotlinlang.org/docs/reference/exceptions.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.