I started to learn Kotlin and I can't understand how to handle exceptions. I know there's no checked ones, but anyway, what should I do if my method throws one? For example:

fun test(a: Int, b: Int) : Int {
    return a / b
}

如果我除以零,我将得到ArithmeticException.那么我该怎么处理这样的事情呢?

推荐答案

ArithmeticException是一个运行时异常,因此在Java中也可以不判断它.处理它的 Select 与Java中的相同:

  • 忽略它并在运行时崩溃
  • Wrap it with a try-catch block. You catch it anywhere up the stack from where it happens, you don't need any throws declarations.

由于Kotlin中没有判断过的异常,因此也没有throws关键字,但如果您混合使用Kotlin和Java,并且希望在Java代码中强制对判断过的异常进行异常处理,则可以使用@Throws注释对方法进行注释.

参见官方Kotlin 文件关于例外情况here.

Kotlin相关问答推荐

如何在使用Kotlin Coroutines时检测和记录何时出现背压

Kotlin异步不并行运行任务

如何使用Kotlinx.LocalDateTime获取重置时间为00:00的当前日期?

我可以更改方法中泛型类的类型参数边界吗?

如何在Spring Boot中注册新的集合工厂

使函数同时挂起和取消挂起

Kotlin .如何用从 1 到 90 的 5 个唯一数字填充列表中的每一行?

MyType.()在 Kotlin 中是什么意思?

如果带注释的成员未被特定块包围,则发出 IDE 警告

使用 LazyListScope 嵌套可组合项

如何从 kotlin 中的数据类访问 val?

Kotlin:如何使用第一个参数的默认值进行函数调用并为第二个参数传递一个值?

如何为 material.Slider 视图创建绑定适配器?

如何在 Kotlin 中判断数组类型(不是泛型类型)

Android Studio 将 Java 转换为 Kotlin 错误无法推断此参数的类型

Spring Boot:更改属性占位符符号

(kotlin的Moshi)@Json vs@field:Json

保存对象时未填充 Spring Boot JPA@CreatedDate @LastModifiedDate

Kotlin扩展函数与成员函数?

使用 Moshi/Retrofit2 访问深度嵌套的 JSON 数组