Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 943
zjuhasz Avatar asked Mar 17 '16 04:03

zjuhasz


People also ask

How do you catch throw exception in Kotlin?

We can use the try-catch block for exception handling in Kotlin. In particular, the code that can throw an exception is put inside the try block. Additionally, the corresponding catch block is used to handle the exception.

Are there checked exceptions in Kotlin?

Kotlin does not have checked exceptions. There are many reasons for this, but we will provide a simple example that illustrates why it is the case. And that's not good. Just take a look at Effective Java, 3rd Edition, Item 77: Don't ignore exceptions.

How do you catch multiple exceptions in Kotlin?

In Kotlin you can do this: try{ } catch(e: MyException1){ } catch(e: MyException2){ } catch(e: MyException3){ } [...]


1 Answers

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.

like image 101
Doug Stevenson Avatar answered Sep 25 '22 14:09

Doug Stevenson