本文介绍了有没有什么简单的方法来看看Kotlin功能抛出什么异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我主要理解检查异常的潜在问题,以及为什么科特林忽略它们。然而,我遇到的问题是,我找不到任何愚蠢的方式清楚地向调用者指出函数可能抛出什么异常。



我在Python中无数次遇到问题,我的程序在运行几个月后会崩溃,因为我没有意识到我正在使用的一些库的功能提出一个特殊的例外。虽然被强制捕获异常可能是相当有问题的,很高兴清楚地看到一个函数可以抛出的所有潜在的异常。



所以回到这个问题,有没有简单的方法来看看功能在Kotlin中抛出什么异常?关于从Kotlin被调用的Java编写的方法呢?即使只是在工具(intelliJ)。我不会在javadoc或kdoc中编写它,因为您使用的函数的作者可能会忽略它。

解决方案

如果您想知道由Kotlin从IntelliJ调用Java方法抛出什么异常,您可以使用F1键快捷方式拉出javadoc,并在弹出菜单中查看throws声明。



Kotlin函数可以声明使用注释。注释显然是可选的,所以你可能不能指望这个永远存在。不幸的是,当您使用@Throws的方法使用F1键盘快捷方式时,它不会显示声明抛出的异常。 Java调用这些方法需要捕获注释中声明的这些异常。



Kotlin javadoc可以使用@throws javadoc注解来进一步提供可以抛出的定义异常一个功能这些确实出现在javadoc和F1帮助弹出窗口中。当然这也是可选的。


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.

解决方案

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.

这篇关于有没有什么简单的方法来看看Kotlin功能抛出什么异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-03 19:50
查看更多