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");
}
But in Kotlin would be something like:
fun testMethod() {
throw Exception("test")
}
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.