Exception

Prerequisites:

try catch

1
2
3
4
5
6
var str: String? = null
try {
    println(str!!.length)
} catch (e: KotlinNullPointerException) {
    e.printStackTrace()
}
Exception in thread "main" java.lang.NullPointerException
	at LearnNullKt.testNull(LearnNull.kt:53)
	at LearnNullKt.main(LearnNull.kt:62)
	at LearnNullKt.main(LearnNull.kt)

自訂例外

Prerequisites:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class MyNullException : RuntimeException("空值")

fun checkNull(str: String?) {
    str ?: throw MyNullException()
}

fun main() {
    var str: String? = null
    try {
        checkNull(str)
    } catch (e: Exception) {
       println(e)
    }
}
MyNullException: 空值

precondition functions

以下是kotlin提供的檢查值為null或值為false,所拋出的異常。

函式 檢查項目 Exception thrown
checkNotNull null IllegalStateException
require false IllegalArgumentException
requireNotNull null IllegalStateException
error null IllegalStateException
assert false AssertError
1
2
3
4
5
6
var str: String? = null
try {
    checkNotNull(str) {"空值"}
} catch (e: Exception) {
   println(e)
}
java.lang.IllegalStateException: 空值

results matching ""

    No results matching ""