1. kotlin 捕获异常
- 不论在 try 块、catch 块中执行怎样的代码(除非退出虚拟机 System.exit(1) ),finally 块的代码总会被执行
const val fileName = "src/com/william/testkt/exception_demo.txt"
fun writeFile(src: String): Int {
var fos: FileOutputStream? = null
try {
val file = File(fileName)
fos = FileOutputStream(file)
fos.write(src.toByteArray())
return 1
} catch (e: Exception) {
e.printStackTrace()
return 2
} finally {
fos?.close()
return 3
}
}
fun readFile(): String {
var fis: FileInputStream? = null
try {
val file = File(fileName)
val size = file.length().toInt()
fis = FileInputStream(file)
val sb = StringBuilder()
val buffer = ByteArray(size)
fis.read(buffer)
sb.append(String(buffer))
return sb.toString()
} catch (e: Exception) {
e.printStackTrace()
return "${e.message}"
} finally {
println("finally")
fis?.close()
}
}
fun main() {
val result = writeFile("this is a simple message")
println(result)
val text = readFile()
println(text)
}
2. kotlin 先处理小异常,再处理大异常
fun compute(obj: String?) {
try {
Integer.parseInt(obj)
} catch (e: RuntimeException) {
println("RuntimeException: ${e.message}")
} catch (e: Exception) {
println("Exception: ${e.message}")
}
}
3. kotlin 使用 throw 抛出异常
fun throwExFun(param: String?) {
if (param == null) {
throw NullPointerException()
}
}
4. kotlin 自定义异常
class CustomException : Exception {
constructor() {}
constructor(msg: String) : super(msg) {}
}
fun throwCustomExFun(param: String?) {
if (param == null) {
throw CustomException("param is null")
}
}
附 Github 源码:
TestException.kt