简体   繁体   English

使用 Kotlin 在方法中抛出异常

[英]throws Exception in a method with Kotlin

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?除了去掉问号,因为没有必要,为什么不以同样的方式处理IOException呢? What is the best approach to handle this situation?处理这种情况的最佳方法是什么?

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.在 Kotlin 中, 没有受检异常,不需要声明异常,并且您不会被迫捕获任何异常,当然,您可以。 Even when deriving from a Java class, you don't have to declare exceptions that a method throws .即使从 Java 类派生,您也不必声明方法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. @Throws(SomeException::class)仅用于 Java 互操作性,它允许编写带有 Java 签名的throws的函数,以便在 Java 中可以(并且必须)处理异常。

Instead, public API exceptions should be documented in KDoc with @throws tag .相反,公共 API 异常应该@throws标签记录在KDoc 中

In Java your functions are something like thisJava 中你的函数是这样的

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

But in Kotlin you can add annotation like below to force other Java classes to catch it.但是在Kotlin 中,您可以添加如下所示的注释来强制其他 Java 类捕获它。 However, as other answers have pointed out, it doesn't have any meaning among Kotlin classes.但是,正如其他答案所指出的那样,它在 Kotlin 类中没有任何意义。

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

Source kotlinlang.org来源kotlinlang.org

All exception classes in Kotlin are descendants of the class Throwable Kotlin中的所有异常类都是Throwable类的后代

@Throws(IOException::class) use this line before the method @Throws(IOException :: class)在方法之前使用此行

Also Use throw like this throw Exception("Hi There!") 还可以像这样使用throw Exception(“ H​​i There!”)

Checkout this for detail explanation https://kotlinlang.org/docs/reference/exceptions.html 查看此以获得详细说明https://kotlinlang.org/docs/reference/exceptions.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM