我怎么知道 Kotlin 中的方法会抛出哪些异常 - Android

How can I know what exceptions could be throw by a method in Kotlin - Android

Java 中很容易知道什么时候必须 try - catch 一段代码,因为编译器强制你这样做并且方法声明有 throws 关键字和Exceptions 将被抛出。

例如:

void testMethod() throws Exception {
    throw new Exception("test");
}

但在 Kotlin 中会是这样的:

fun testMethod() {
    throw Exception("test")
}

在Kotlin中如何知道class提供的一段代码需要为某个Exception处理?

我不知道我是否必须处理 Exception,或者我是否可以更具体地处理 IOExcepcion

编辑 2021 年 9 月 16 日:

经过更多的调查,我发现这个“问题”没有解决方案。

2016 年有一个相关问题面临同样的问题:

这个答案很好地恢复了可以做什么:

If you want to know what exceptions a Java method throws when called by Kotlin from IntelliJ, you can use the F1 key shortcut to pull up the javadoc and see the throws declaration in the popup menu.

Kotlin functions can declare exceptions that it throws using the @Throws annotation. Annotations are obviously optional, so you probably can't expect this to always exist. Unfortunately, when you use the F1 keyboard shortcut on a method using @Throws, it doesn't show the exceptions declared to be thrown. Java calls into these methods are required to catch these exceptions declared in the annotation.

Kotlin javadoc can use the @throws javadoc annotation to further provide definition exceptions that can be thrown in a function. These do appear in javadoc and in F1 help popups. An of course this is also optional.

科特林 doesn't have checked exceptions, consequentially there is no catch or specify requirement。所以不需要在函数头中指定任何检查异常。

这也意味着 kotlin will not force you to catch checked exceptions 从任何 java 代码中抛出。是否要捕获此类异常由您决定,也可以选择不捕获。

如果你想与 java 互操作,那么你可以使用 @Throws

@Throws(IOException::class)
fun readFile(name: String): String {...}

// this will be translated to

String readFile(String name) throws IOException {...}

答案是你不知道 除了它在其文档中所说的以外,Kotlin 方法可以抛出哪些异常。 Kotlin 的设计者故意忽略了该功能。

具体来说,他们得出的结论是,强制捕获异常比其价值更麻烦。 很多 Java 代码实际上并没有真正处理它应该处理的已检查异常,最终花费了大量样板只是将它们扔掉或记录它们并忽略它们.使用函数式编程处理检查异常特别困难,您必须有专门的 lambda 可以抛出检查异常。