java - 我如何知道 Kotlin 中的方法可能引发哪些异常 - Android

标签 java android kotlin exception

Java很容易知道什么时候必须 try - catch一段代码,因为编译器强制你这样做,并且方法声明有 throws带有 Exceptions 的关键字那将被抛出。
例如:

void testMethod() throws Exception {
    throw new Exception("test");
}
但在 Kotlin 中会是这样的:
fun testMethod() {
    throw Exception("test")
}
在 Kotlin 中如何知道某个类提供的一段代码需要处理 Exception ?
我不知道我是否必须处理 Exception ,或者如果我可以更具体地使用 IOExcepcion编辑 2021 年 9 月 16 日:
经过更多的调查,我发现这个“问题”没有解决办法。
2016 年有一个相关问题面临同样的问题:Is there any easy way to see what exceptions a Kotlin function throws?
这个答案很好地恢复了可以做的事情:

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 方法可以抛出哪些异常,除了它在文档中所说的。 Kotlin 的设计者故意忽略了这个功能。
具体来说,他们得出的结论是,强制捕获异常比它的值(value)更麻烦。许多 Java 代码实际上并没有真正处理它应该处理的检查异常,并且最终花费大量样板文件将它们丢弃或记录它们并忽略它们。使用函数式编程处理检查的异常特别困难,在这种情况下,您必须拥有可以抛出检查异常的专用 lambda。

关于java - 我如何知道 Kotlin 中的方法可能引发哪些异常 - Android,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69189879/

相关文章:

java - 我搜索非二叉树(n 叉树)的方法有什么问题?

android - 使用模式启动谷歌地图方向 Intent

lambda - 如何在Kotlin中序列化Lambda

android - 在 Android OrmLite 中使用多个数据库助手

kotlin - 等待使用协程绑定(bind)服务

Kotlin 与 Objective-C 框架的多平台/原生互操作性

java - 在Java中,这个 "double cannot be dereferenced"错误是什么意思?

java - (应使用 insert ="false"update ="false"进行映射)

java - 在Java中定义自定义数组类型

android - 最近使用的安卓应用