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

a 夏天 提交于 2019-12-10 12:32:38

问题


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.


回答1:


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.




回答2:


This library called Result is a nice solution. It returns a Result object with a value or an exception and changes its type to success or failure accordingly. They can also be chained together using the libraries map and flatmap functions which helps eliminate nested try-catch blocks. Very cool, I recommend anyone who finds this question check it out.

Of course this only helps with functions that take advantage of it so I'm not marking this as an answer.



来源:https://stackoverflow.com/questions/36051508/is-there-any-easy-way-to-see-what-exceptions-a-kotlin-function-throws

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!