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

Bog*_*oid 4 java android exception kotlin

In Java it's easy to know when you have to try - catch a piece of code because the compiler force you to do it and the method declaration have the throws keyword with the Exceptions that will be throw.

For example:

void testMethod() throws Exception {
    throw new Exception("test");
}
Run Code Online (Sandbox Code Playgroud)

But in Kotlin would be something like:

fun testMethod() {
    throw Exception("test")
}
Run Code Online (Sandbox Code Playgroud)

How can I know in Kotlin that a piece of code provided by a class need to be handled for a certain Exception?

I can't know if I have to handle a Exception, or if I can be more specific with a IOExcepcion

Edit 16/09/2021:

After more investigation, I found that there is no solution to this "problem".

There is a related question from 2016 facing the same issue: Is there any easy way to see what exceptions a Kotlin function throws?

And this answer resume very well what could be done:

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.

Lou*_*man 5

答案是,除了文档中所述之外,您不知道 Kotlin 方法可以抛出哪些异常。Kotlin 的设计者故意忽略了这个功能。

具体来说,他们得出的结论是,强制捕获异常麻烦多于其价值。许多Java 代码实际上并没有真正处理它应该处理的已检查异常,最终花费了大量的样板文件只是将它们丢弃或记录它们并忽略它们检查异常在函数式编程中特别难以处理,在函数式编程中,您必须有专门的 lambda 表达式来抛出检查异常。