Kotlin中的异常和Java中的异常相似
if (percentage !in 0..100){
throw IllegalArgumentException("出现异常啦!")
}
Kotlin中不使用new关键字来创建异常实例
和Java不同的是Kotlin中throw结构是一个表达式,能作为另一个表达式的一部分使用
var value = 10
var percentage = if (value in 0..100) {
value
} else {
throw IllegalArgumentException("出现异常了!")
}
try catch finally
fun readNumber(reader: BufferedReader): Int? {
try {
val line = reader.readLine()
return Integer.parseInt(line)
} catch (e: NumberFormatException) {
return null
} finally {
reader.close()
}
}
把try 当做表达式来使用
fun readNum(reader: BufferedReader) {
val number = try {
val line = reader.readLine()
Integer.parseInt(line)
} catch (e: NumberFormatException) {
return
}
}
在catch中返回值
fun readNum(reader: BufferedReader) {
val number = try {
val line = reader.readLine()
Integer.parseInt(line)
} catch (e: NumberFormatException) {
null
}
}