【发布时间】:2018-08-30 14:21:24
【问题描述】:
我使用的是 Kotlin 1.2.60。
val someString: String = try {
String.format("Okay %s", "there") // or any function that returns String
} catch(exception: Exception) {
try {
// fun incrementErrorCount() { ... }
incrementErrorCount() // [1] Error: Type mismatch: Inferred type is Unit but String was expected
} finally {
throw exception
}
// throw exception // [2] Fixes the type mismatch when uncommented, but raises Warning: Unreachable code
}
我在 1 收到 类型不匹配 错误,因为它期望 incrementErrorCount() 返回一个字符串 - 但返回类型应该无关紧要,因为它总是会重新抛出 @ 987654324@反正。
我添加了2,它修复了类型不匹配 错误,但引发了无法访问代码 警告,因为函数永远不会超出throw 中的finally .
我做错了什么?我怎样才能让它编译没有错误或警告?
【问题讨论】:
-
如果你有什么方法抛出异常,为什么要使用
finally块?直接在try块之后编写 throw 异常,这将使其成为catch块的最后一条语句。
标签: kotlin