我有Java背景,最近开始学习Kotlin。现在我正在读一本书“Programming Kotlin”,我看到了一个带有 try-catch 表达式的片段。这促使我编写了一些简单的函数来比较它在 Java 和 Kotlin 中的工作方式。第一个功能:
fun tryExpExplicit(throwing: Boolean): Int {
return try {
if (throwing) {
throw RuntimeException()
}
return 1
} catch (e: Exception) {
return 2
} finally {
return 3
}
}
Run Code Online (Sandbox Code Playgroud)
按我的预期工作并且总是返回 3。
出乎意料的是,当我使用隐式返回时,行为不同
fun tryExpImplicit(throwing: Boolean): Int {
return try {
if (throwing) {
throw RuntimeException()
}
1
} catch (e: Exception) {
2
} finally {
3
}
}
Run Code Online (Sandbox Code Playgroud)
并且 3 永远不会返回。
为什么这两个函数的工作方式不同?