Java 使用 Kotlin 在方法中抛出异常
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36528515/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
throws Exception in a method with Kotlin
提问by cesards
I'm trying to convert this Java code to Kotlin:
我正在尝试将此 Java 代码转换为 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.
我发现谈论在 Kotlin 中抛出异常的唯一信息是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?
除了去掉问号,因为没有必要,为什么不IOException
一样处理呢?处理这种情况的最佳方法是什么?
采纳答案by hotkey
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
.
在 Kotlin 中,没有受检异常,不需要声明异常,并且您不会被迫捕获任何异常,当然,您可以。即使从 Java 类派生,您也不必声明方法的异常throws
。
@Throws(SomeException::class)
is just a mean of Java interoperability, it 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.
@Throws(SomeException::class)
只是 Java 互操作性的一种手段,它允许人们用throws
Java 签名编写一个函数,以便在 Java 中处理异常是可能的(并且是必要的)。
Instead, public API exceptions should be documented in KDoc with @throws
tag.
相反,公共 API 异常应该在KDoc 中用@throws
标签记录。
回答by Radesh
In Javayour functions are something like this
在Java 中你的函数是这样的
void foo() throws IOException{
throw new IOException();
}
But in Kotlinyou 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.
但是在Kotlin 中,您可以添加如下所示的注释来强制其他 Java 类捕获它。但是,正如其他答案所指出的那样,它在 Kotlin 类中没有任何意义。
@Throws(IOException::class)
fun foo() {
throw IOException()
}
Source kotlinlang.org