String string = null;
string.length();
Runtime才能知道錯誤
//可以null
var name: String?
//不能null
var name2: String
var name: String? = null
println(name.length)
fun main() {
var name: String? = null
setName(name)
}
fun setName(str: String) {
//不可能會有null進來了
}
fun setName2(str: String?) {
//要處理null
}
fun main() {
var str = getName()
}
fun getName() : String?{
return "A"
}
fun main() {
getLocation("地址")
}
//找座標,用Location?來表示找不到
fun getLocation(address: String) : Location?{
if(找不到){
return null
}
return Location(22.22,124.22)
}
class Location (val lat:Double, val lng:Double)
var name2 = "A"
name2 = null
var lenght = name?.length ?: 0
var a: Int ?
var b:Boolean?
Exception 用來表達程式出了問題
throw Exception("Hi There!")
fun division(a:Int, b:Int) :Int{
if (b == 0) {
throw Exception("b不可為0")
}
return a/b
}
在不適合的時間呼叫此方法
try {
// some code
}
catch (e: SomeException) {
// handler
}
finally {
// optional finally block
}
try {
log.append(message)
}
catch (IOException e) {
// Must be safe
}
fun main() {
try {
callAPI()
}catch (e:Exception){
when (e) {
is APIFail -> {
println("API Fail的處理")
}
is APIForbidden -> {
println("API Forbidden 的處理")
}
}
}
}
fun callAPI(): String {
throw APIFail()
}
class APIFail():RuntimeException()
class APIForbidden():RuntimeException(
checkNotNull
如果參數是null,拋出IllegalStateException異常,否則回傳參數值
require
如果參數是false,拋出IllegalArgumentException異常
requireNotNull
如果參數是null,拋出IllegalStateException異常,否則回傳參數值
error
拋出異常訊息
assert
如果參數是false,拋出AssertionError異常