intellij-ideaexceptionkotlinunchecked-exception

Is there any easy way to see what exceptions a Kotlin function throws?


I mostly understand the potential issues with checked exceptions and why Kotlin omits them. However, the issue I am encountering is I can't find any foolproof way of clearly indicating to the caller what exceptions a function may throw.

I have run into the issue countless times in Python where my program will crash after running for months because I didn't realise a function from some library I'm using can raise a particular exception. Although being forced to catch exceptions can be quite problematic, it is nice to clearly see all the potential exceptions a function can throw.

So back to the question, is there any simple way to see what exceptions a function throws in Kotlin? What about for methods written in Java that are being called from Kotlin? Even if just in tooling (intelliJ). I'm not counting writing it in javadoc or kdoc as the writer of the function you're using may have omitted it.


Solution

  • 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.